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

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

# Add the following lines to /etc/rc.conf to enable wildfly90:
# wildfly90_enable (bool):      Set to "YES" to enable wildfly90
# wildfly90_args (str):         Optional arguments to OAJBoss
# wildfly90_log_stdout (str)       JBoss log output stdout, filename.
# wildfly90_log_stderr (str)       JBoss log output stderr, filename.
#

. /etc/rc.subr

name="wildfly90"
rcvar=wildfly90_enable
extra_commands="status"

load_rc_config $name

wildfly90_logdir="/var/log/wildfly90"
wildfly90_enable="${wildfly90_enable:-"NO"}"
wildfly90_log_stdout="${wildfly90_log_stdout:-"${wildfly90_logdir}/log"}"
wildfly90_log_stderr="${wildfly90_log_stderr:-"${wildfly90_logdir}/error"}"
wildfly90_args="${wildfly90_args:-""}"
wildfly90_sleep="${wildfly90_sleep:-"5"}"
wildfly90_kill9="${wildfly90_kill9:-""}"
wildfly90_additional_killall="${wildfly90_additional_killall:-""}"
wildfly90_user="www"
wildfly90_group="www"

start_cmd="wildfly90_start"
stop_cmd="wildfly90_stop"
pidfile="/var/run/wildfly90.pid"
status_cmd="wildfly90_status"

WILDFLY_HOME="/usr/local/wildfly-9.0.2"

wildfly90_start ()
{
	if [ ! -d "${wildfly90_logdir}" ]
	then
		install -d -o ${wildfly90_user} ${wildfly90_logdir}
	fi

	echo "wildfly90: making sure all writeable dirs belong to proper user/group"
	chown -R ${wildfly90_user}:${wildfly90_group} ${WILDFLY_HOME}/standalone
	echo "Starting wildfly90."
	daemon -u ${wildfly90_user} ${WILDFLY_HOME}/bin/standalone.sh ${wildfly90_args} >> ${wildfly90_log_stdout} 2>> ${wildfly90_log_stderr}

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

wildfly90_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 "${wildfly90_kill9}" ]
		then
			sleep ${wildfly90_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 "${wildfly90_additional_killall}" ]
		then
			sleep ${wildfly90_sleep}
			killall ${wildfly90_additional_killall}
		fi
		rm ${pidfile}
	fi
}

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

run_rc_command "$1"
