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

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

# Add the following lines to /etc/rc.conf to enable wildfly17:
# wildfly17_enable (bool):      Set to "YES" to enable wildfly17
# wildfly17_args (str):         Optional arguments to OAJBoss
# wildfly17_log_stdout (str)       JBoss log output stdout, filename.
# wildfly17_log_stderr (str)       JBoss log output stderr, filename.
#

. /etc/rc.subr

name="wildfly17"
rcvar=wildfly17_enable
extra_commands="status"

load_rc_config $name

wildfly17_logdir="/var/log/wildfly17"
wildfly17_enable="${wildfly17_enable:-"NO"}"
wildfly17_log_stdout="${wildfly17_log_stdout:-"${wildfly17_logdir}/log"}"
wildfly17_log_stderr="${wildfly17_log_stderr:-"${wildfly17_logdir}/error"}"
wildfly17_args="${wildfly17_args:-""}"
wildfly17_sleep="${wildfly17_sleep:-"5"}"
wildfly17_kill9="${wildfly17_kill9:-""}"
wildfly17_additional_killall="${wildfly17_additional_killall:-""}"
wildfly17_user="www"
wildfly17_group="www"

start_cmd="wildfly17_start"
stop_cmd="wildfly17_stop"
pidfile="/var/run/wildfly17.pid"
status_cmd="wildfly17_status"

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

wildfly17_start ()
{
	if [ ! -d "${wildfly17_logdir}" ]
	then
		install -d -o ${wildfly17_user} ${wildfly17_logdir}
	fi

	echo "wildfly17: making sure all writeable dirs belong to proper user/group"
	chown -R ${wildfly17_user}:${wildfly17_group} ${WILDFLY_HOME}/standalone
	echo "Starting wildfly17."
	daemon -u ${wildfly17_user} ${WILDFLY_HOME}/bin/standalone.sh ${wildfly17_args} >> ${wildfly17_log_stdout} 2>> ${wildfly17_log_stderr}

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

wildfly17_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 "${wildfly17_kill9}" ]
		then
			sleep ${wildfly17_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 "${wildfly17_additional_killall}" ]
		then
			sleep ${wildfly17_sleep}
			killall ${wildfly17_additional_killall}
		fi
		rm ${pidfile}
	fi
}

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

run_rc_command "$1"
