#!/bin/sh
#
# wildfly13 startup script.
#
# $FreeBSD$

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

# Add the following lines to /etc/rc.conf to enable wildfly13:
# wildfly13_enable (bool):      Set to "YES" to enable wildfly13
# wildfly13_args (str):         Optional arguments to OAJBoss
# wildfly13_log_stdout (str)       JBoss log output stdout, filename.
# wildfly13_log_stderr (str)       JBoss log output stderr, filename.
#

. /etc/rc.subr

name="wildfly13"
rcvar=wildfly13_enable
extra_commands="status"

load_rc_config $name

wildfly13_logdir="/var/log/wildfly13"
wildfly13_enable="${wildfly13_enable:-"NO"}"
wildfly13_log_stdout="${wildfly13_log_stdout:-"${wildfly13_logdir}/log"}"
wildfly13_log_stderr="${wildfly13_log_stderr:-"${wildfly13_logdir}/error"}"
wildfly13_args="${wildfly13_args:-""}"
wildfly13_sleep="${wildfly13_sleep:-"5"}"
wildfly13_kill9="${wildfly13_kill9:-""}"
wildfly13_additional_killall="${wildfly13_additional_killall:-""}"
wildfly13_user="www"
wildfly13_group="www"

start_cmd="wildfly13_start"
stop_cmd="wildfly13_stop"
pidfile="/var/run/wildfly13.pid"
status_cmd="wildfly13_status"

WILDFLY_HOME="/usr/local/wildfly13"

wildfly13_start ()
{
	if [ ! -d "${wildfly13_logdir}" ]
	then
		install -d -o ${wildfly13_user} ${wildfly13_logdir}
	fi

	echo "wildfly13: making sure all writeable dirs belong to proper user/group"
	chown -R ${wildfly13_user}:${wildfly13_group} ${WILDFLY_HOME}/standalone
	echo "Starting wildfly13."
	daemon -u ${wildfly13_user} ${WILDFLY_HOME}/bin/standalone.sh ${wildfly13_args} >> ${wildfly13_log_stdout} 2>> ${wildfly13_log_stderr}

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

wildfly13_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 "${wildfly13_kill9}" ]
		then
			sleep ${wildfly13_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 "${wildfly13_additional_killall}" ]
		then
			sleep ${wildfly13_sleep}
			killall ${wildfly13_additional_killall}
		fi
		rm ${pidfile}
	fi
}

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

run_rc_command "$1"
