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

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

# Add the following lines to /etc/rc.conf to enable wildfly15:
# wildfly15_enable (bool):      Set to "YES" to enable wildfly15
# wildfly15_args (str):         Optional arguments to OAJBoss
# wildfly15_log_stdout (str)       JBoss log output stdout, filename.
# wildfly15_log_stderr (str)       JBoss log output stderr, filename.
#

. /etc/rc.subr

name="wildfly15"
rcvar=wildfly15_enable
extra_commands="status"

load_rc_config $name

wildfly15_logdir="/var/log/wildfly15"
wildfly15_enable="${wildfly15_enable:-"NO"}"
wildfly15_log_stdout="${wildfly15_log_stdout:-"${wildfly15_logdir}/log"}"
wildfly15_log_stderr="${wildfly15_log_stderr:-"${wildfly15_logdir}/error"}"
wildfly15_args="${wildfly15_args:-""}"
wildfly15_sleep="${wildfly15_sleep:-"5"}"
wildfly15_kill9="${wildfly15_kill9:-""}"
wildfly15_additional_killall="${wildfly15_additional_killall:-""}"
wildfly15_user="www"
wildfly15_group="www"

start_cmd="wildfly15_start"
stop_cmd="wildfly15_stop"
pidfile="/var/run/wildfly15.pid"
status_cmd="wildfly15_status"

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

wildfly15_start ()
{
	if [ ! -d "${wildfly15_logdir}" ]
	then
		install -d -o ${wildfly15_user} ${wildfly15_logdir}
	fi

	echo "wildfly15: making sure all writeable dirs belong to proper user/group"
	chown -R ${wildfly15_user}:${wildfly15_group} ${WILDFLY_HOME}/standalone
	echo "Starting wildfly15."
	daemon -u ${wildfly15_user} ${WILDFLY_HOME}/bin/standalone.sh ${wildfly15_args} >> ${wildfly15_log_stdout} 2>> ${wildfly15_log_stderr}

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

wildfly15_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 "${wildfly15_kill9}" ]
		then
			sleep ${wildfly15_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 "${wildfly15_additional_killall}" ]
		then
			sleep ${wildfly15_sleep}
			killall ${wildfly15_additional_killall}
		fi
		rm ${pidfile}
	fi
}

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

run_rc_command "$1"
