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

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

# Add the following lines to /etc/rc.conf to enable wildfly18:
# wildfly18_enable (bool):      Set to "YES" to enable wildfly18
# wildfly18_args (str):         Optional arguments to OAJBoss
# wildfly18_log_stdout (str)       JBoss log output stdout, filename.
# wildfly18_log_stderr (str)       JBoss log output stderr, filename.
#

. /etc/rc.subr

name="wildfly18"
rcvar=wildfly18_enable
extra_commands="status"

load_rc_config $name

wildfly18_logdir="/var/log/wildfly18"
wildfly18_enable="${wildfly18_enable:-"NO"}"
wildfly18_log_stdout="${wildfly18_log_stdout:-"${wildfly18_logdir}/log"}"
wildfly18_log_stderr="${wildfly18_log_stderr:-"${wildfly18_logdir}/error"}"
wildfly18_args="${wildfly18_args:-""}"
wildfly18_sleep="${wildfly18_sleep:-"5"}"
wildfly18_kill9="${wildfly18_kill9:-""}"
wildfly18_additional_killall="${wildfly18_additional_killall:-""}"
wildfly18_user="www"
wildfly18_group="www"

start_cmd="wildfly18_start"
stop_cmd="wildfly18_stop"
pidfile="/var/run/wildfly18.pid"
status_cmd="wildfly18_status"

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

wildfly18_start ()
{
	if [ ! -d "${wildfly18_logdir}" ]
	then
		install -d -o ${wildfly18_user} ${wildfly18_logdir}
	fi

	echo "wildfly18: making sure all writeable dirs belong to proper user/group"
	chown -R ${wildfly18_user}:${wildfly18_group} ${WILDFLY_HOME}/standalone
	echo "Starting wildfly18."
	daemon -u ${wildfly18_user} ${WILDFLY_HOME}/bin/standalone.sh ${wildfly18_args} >> ${wildfly18_log_stdout} 2>> ${wildfly18_log_stderr}

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

wildfly18_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 "${wildfly18_kill9}" ]
		then
			sleep ${wildfly18_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 "${wildfly18_additional_killall}" ]
		then
			sleep ${wildfly18_sleep}
			killall ${wildfly18_additional_killall}
		fi
		rm ${pidfile}
	fi
}

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

run_rc_command "$1"
