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

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

# Add the following lines to /etc/rc.conf to enable wildfly25:
# wildfly25_enable (bool):      Set to "YES" to enable wildfly25
# wildfly25_args (str):         Optional arguments to OAJBoss
# wildfly25_log_stdout (str)       JBoss log output stdout, filename.
# wildfly25_log_stderr (str)       JBoss log output stderr, filename.
#

. /etc/rc.subr

name="wildfly25"
rcvar=wildfly25_enable
extra_commands="status"

load_rc_config $name

wildfly25_logdir="/var/log/wildfly25"
wildfly25_enable="${wildfly25_enable:-"NO"}"
wildfly25_log_stdout="${wildfly25_log_stdout:-"${wildfly25_logdir}/log"}"
wildfly25_log_stderr="${wildfly25_log_stderr:-"${wildfly25_logdir}/error"}"
wildfly25_args="${wildfly25_args:-""}"
wildfly25_sleep="${wildfly25_sleep:-"5"}"
wildfly25_kill9="${wildfly25_kill9:-""}"
wildfly25_additional_killall="${wildfly25_additional_killall:-""}"
wildfly25_user="www"
wildfly25_group="www"

start_cmd="wildfly25_start"
stop_cmd="wildfly25_stop"
pidfile="/var/run/wildfly25.pid"
status_cmd="wildfly25_status"

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

wildfly25_start ()
{
	if [ ! -d "${wildfly25_logdir}" ]
	then
		install -d -o ${wildfly25_user} ${wildfly25_logdir}
	fi

	echo "wildfly25: making sure all writeable dirs belong to proper user/group"
	chown -R ${wildfly25_user}:${wildfly25_group} ${WILDFLY_HOME}/standalone
	echo "Starting wildfly25."
	daemon -u ${wildfly25_user} ${WILDFLY_HOME}/bin/standalone.sh ${wildfly25_args} >> ${wildfly25_log_stdout} 2>> ${wildfly25_log_stderr}

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

wildfly25_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 "${wildfly25_kill9}" ]
		then
			sleep ${wildfly25_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 "${wildfly25_additional_killall}" ]
		then
			sleep ${wildfly25_sleep}
			killall ${wildfly25_additional_killall}
		fi
		rm ${pidfile}
	fi
}

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

run_rc_command "$1"
