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

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

# Add the following lines to /etc/rc.conf to enable wildfly16:
# wildfly16_enable (bool):      Set to "YES" to enable wildfly16
# wildfly16_args (str):         Optional arguments to OAJBoss
# wildfly16_log_stdout (str)       JBoss log output stdout, filename.
# wildfly16_log_stderr (str)       JBoss log output stderr, filename.
#

. /etc/rc.subr

name="wildfly16"
rcvar=wildfly16_enable
extra_commands="status"

load_rc_config $name

wildfly16_logdir="/var/log/wildfly16"
wildfly16_enable="${wildfly16_enable:-"NO"}"
wildfly16_log_stdout="${wildfly16_log_stdout:-"${wildfly16_logdir}/log"}"
wildfly16_log_stderr="${wildfly16_log_stderr:-"${wildfly16_logdir}/error"}"
wildfly16_args="${wildfly16_args:-""}"
wildfly16_sleep="${wildfly16_sleep:-"5"}"
wildfly16_kill9="${wildfly16_kill9:-""}"
wildfly16_additional_killall="${wildfly16_additional_killall:-""}"
wildfly16_user="www"
wildfly16_group="www"

start_cmd="wildfly16_start"
stop_cmd="wildfly16_stop"
pidfile="/var/run/wildfly16.pid"
status_cmd="wildfly16_status"

WILDFLY_HOME="/usr/local/wildfly16"
#minimal requirements must be set for our javavmwrapper
JAVA_VERSION="1.8+"
export JAVA_VERSION

wildfly16_start ()
{
	if [ ! -d "${wildfly16_logdir}" ]
	then
		install -d -o ${wildfly16_user} ${wildfly16_logdir}
	fi

	echo "wildfly16: making sure all writeable dirs belong to proper user/group"
	chown -R ${wildfly16_user}:${wildfly16_group} ${WILDFLY_HOME}/standalone
	echo "Starting wildfly16."
	daemon -u ${wildfly16_user} ${WILDFLY_HOME}/bin/standalone.sh ${wildfly16_args} >> ${wildfly16_log_stdout} 2>> ${wildfly16_log_stderr}

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

wildfly16_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 "${wildfly16_kill9}" ]
		then
			sleep ${wildfly16_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 "${wildfly16_additional_killall}" ]
		then
			sleep ${wildfly16_sleep}
			killall ${wildfly16_additional_killall}
		fi
		rm ${pidfile}
	fi
}

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

run_rc_command "$1"
