#!/bin/sh
#
# wildfly10 startup script.
#
# $FreeBSD: head/java/wildfly10/files/wildfly10.in 518482 2019-11-26 21:46:12Z jkim $
#

# PROVIDE: wildfly10
# REQUIRE: NETWORKING SERVERS
# KEYWORD: shutdown

# Add the following lines to /etc/rc.conf to enable wildfly10:
# wildfly10_enable (bool):      Set to "YES" to enable wildfly10
# wildfly10_args (str):         Optional arguments to OAJBoss
# wildfly10_log_stdout (str)       JBoss log output stdout, filename.
# wildfly10_log_stderr (str)       JBoss log output stderr, filename.
#

. /etc/rc.subr

name="wildfly10"
rcvar=wildfly10_enable
extra_commands="status"

load_rc_config $name

wildfly10_logdir="/var/log/wildfly10"
wildfly10_enable="${wildfly10_enable:-"NO"}"
wildfly10_log_stdout="${wildfly10_log_stdout:-"${wildfly10_logdir}/log"}"
wildfly10_log_stderr="${wildfly10_log_stderr:-"${wildfly10_logdir}/error"}"
wildfly10_args="${wildfly10_args:-""}"
wildfly10_sleep="${wildfly10_sleep:-"5"}"
wildfly10_kill9="${wildfly10_kill9:-""}"
wildfly10_additional_killall="${wildfly10_additional_killall:-""}"
wildfly10_user="www"
wildfly10_group="www"

start_cmd="wildfly10_start"
stop_cmd="wildfly10_stop"
pidfile="/var/run/wildfly10.pid"
status_cmd="wildfly10_status"

WILDFLY_HOME="/usr/local/wildfly10"

wildfly10_start ()
{
	if [ ! -d "${wildfly10_logdir}" ]
	then
		install -d -o ${wildfly10_user} ${wildfly10_logdir}
	fi

	echo "wildfly10: making sure all writeable dirs belong to proper user/group"
	chown -R ${wildfly10_user}:${wildfly10_group} ${WILDFLY_HOME}/standalone
	echo "Starting wildfly10."
	daemon -u ${wildfly10_user} ${WILDFLY_HOME}/bin/standalone.sh ${wildfly10_args} >> ${wildfly10_log_stdout} 2>> ${wildfly10_log_stderr}

	sleep ${wildfly10_sleep}	# let daemon(8) and sh(1) finish before executing pgrep(1)
	pgrep -U ${wildfly10_user} -f ${WILDFLY_HOME}/modules > ${pidfile}
	chown ${wildfly10_user} $pidfile
}

wildfly10_stop ()
{
	# Subvert the check_pid_file procname check.
	if [ -f ${pidfile} ]
	then
		kill `cat ${pidfile}`
		# Only if we aware that our setup can hangs, and only after trying simple kill, we can kill it hard way.
		if [ ! -z "${wildfly10_kill9}" ]
		then
			sleep ${wildfly10_sleep}
			kill  -9 `cat ${pidfile}`
		fi
		# In some setups, JBoss can spawn some child processess, which could prevent it from stopping, and freeing net ports.
		# Let's blindly kill them all, since we are really know what we are doing.
		if [ ! -z "${wildfly10_additional_killall}" ]
		then
			sleep ${wildfly10_sleep}
			killall ${wildfly10_additional_killall}
		fi
		rm ${pidfile}
	fi
}

wildfly10_status ()
{
	# If running, show pid
	if [ -f ${pidfile} ]
	then
		echo "wildfly10 is running as pid" `cat ${pidfile}`
	else
		echo "wildfly10 is not running"
	fi
}

run_rc_command "$1"
