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

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

# Add the following lines to /etc/rc.conf to enable wildfly26:
# wildfly26_enable (bool):      Set to "YES" to enable wildfly26
# wildfly26_args (str):         Optional arguments to OAJBoss
# wildfly26_log_stdout (str)       JBoss log output stdout, filename.
# wildfly26_log_stderr (str)       JBoss log output stderr, filename.
#

. /etc/rc.subr

name="wildfly26"
rcvar=wildfly26_enable
extra_commands="status"

load_rc_config $name

wildfly26_logdir="/var/log/wildfly26"
wildfly26_enable="${wildfly26_enable:-"NO"}"
wildfly26_log_stdout="${wildfly26_log_stdout:-"${wildfly26_logdir}/log"}"
wildfly26_log_stderr="${wildfly26_log_stderr:-"${wildfly26_logdir}/error"}"
wildfly26_args="${wildfly26_args:-""}"
wildfly26_sleep="${wildfly26_sleep:-"5"}"
wildfly26_kill9="${wildfly26_kill9:-""}"
wildfly26_additional_killall="${wildfly26_additional_killall:-""}"
wildfly26_user="www"
wildfly26_group="www"

start_cmd="wildfly26_start"
stop_cmd="wildfly26_stop"
pidfile="/var/run/wildfly26.pid"
status_cmd="wildfly26_status"

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

wildfly26_start ()
{
	if [ ! -d "${wildfly26_logdir}" ]
	then
		install -d -o ${wildfly26_user} ${wildfly26_logdir}
	fi

	echo "wildfly26: making sure all writeable dirs belong to proper user/group"
	chown -R ${wildfly26_user}:${wildfly26_group} ${WILDFLY_HOME}/standalone
	echo "Starting wildfly26."
	daemon -u ${wildfly26_user} ${WILDFLY_HOME}/bin/standalone.sh ${wildfly26_args} >> ${wildfly26_log_stdout} 2>> ${wildfly26_log_stderr}

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

wildfly26_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 "${wildfly26_kill9}" ]
		then
			sleep ${wildfly26_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 "${wildfly26_additional_killall}" ]
		then
			sleep ${wildfly26_sleep}
			killall ${wildfly26_additional_killall}
		fi
		rm ${pidfile}
	fi
}

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

run_rc_command "$1"
