#!/bin/sh
#
# wildfly11 startup script.

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

# Add the following lines to /etc/rc.conf to enable wildfly11:
# wildfly11_enable (bool):      Set to "YES" to enable wildfly11
# wildfly11_args (str):         Optional arguments to OAJBoss
# wildfly11_log_stdout (str)       JBoss log output stdout, filename.
# wildfly11_log_stderr (str)       JBoss log output stderr, filename.
#

. /etc/rc.subr

name="wildfly11"
rcvar=wildfly11_enable
extra_commands="status"

load_rc_config $name

wildfly11_logdir="/var/log/wildfly11"
wildfly11_enable="${wildfly11_enable:-"NO"}"
wildfly11_log_stdout="${wildfly11_log_stdout:-"${wildfly11_logdir}/log"}"
wildfly11_log_stderr="${wildfly11_log_stderr:-"${wildfly11_logdir}/error"}"
wildfly11_args="${wildfly11_args:-""}"
wildfly11_sleep="${wildfly11_sleep:-"5"}"
wildfly11_kill9="${wildfly11_kill9:-""}"
wildfly11_additional_killall="${wildfly11_additional_killall:-""}"
wildfly11_user="www"
wildfly11_group="www"

start_cmd="wildfly11_start"
stop_cmd="wildfly11_stop"
pidfile="/var/run/wildfly11.pid"
status_cmd="wildfly11_status"

WILDFLY_HOME="/usr/local/wildfly11"

wildfly11_start ()
{
	if [ ! -d "${wildfly11_logdir}" ]
	then
		install -d -o ${wildfly11_user} ${wildfly11_logdir}
	fi

	echo "wildfly11: making sure all writeable dirs belong to proper user/group"
	chown -R ${wildfly11_user}:${wildfly11_group} ${WILDFLY_HOME}/standalone
	echo "Starting wildfly11."
	daemon -u ${wildfly11_user} ${WILDFLY_HOME}/bin/standalone.sh ${wildfly11_args} >> ${wildfly11_log_stdout} 2>> ${wildfly11_log_stderr}

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

wildfly11_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 "${wildfly11_kill9}" ]
		then
			sleep ${wildfly11_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 "${wildfly11_additional_killall}" ]
		then
			sleep ${wildfly11_sleep}
			killall ${wildfly11_additional_killall}
		fi
		rm ${pidfile}
	fi
}

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

run_rc_command "$1"
