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

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

# Add the following lines to /etc/rc.conf to enable wildfly14:
# wildfly14_enable (bool):      Set to "YES" to enable wildfly14
# wildfly14_args (str):         Optional arguments to OAJBoss
# wildfly14_log_stdout (str)       JBoss log output stdout, filename.
# wildfly14_log_stderr (str)       JBoss log output stderr, filename.
#

. /etc/rc.subr

name="wildfly14"
rcvar=wildfly14_enable
extra_commands="status"

load_rc_config $name

wildfly14_logdir="/var/log/wildfly14"
wildfly14_enable="${wildfly14_enable:-"NO"}"
wildfly14_log_stdout="${wildfly14_log_stdout:-"${wildfly14_logdir}/log"}"
wildfly14_log_stderr="${wildfly14_log_stderr:-"${wildfly14_logdir}/error"}"
wildfly14_args="${wildfly14_args:-""}"
wildfly14_sleep="${wildfly14_sleep:-"5"}"
wildfly14_kill9="${wildfly14_kill9:-""}"
wildfly14_additional_killall="${wildfly14_additional_killall:-""}"
wildfly14_user="www"
wildfly14_group="www"

start_cmd="wildfly14_start"
stop_cmd="wildfly14_stop"
pidfile="/var/run/wildfly14.pid"
status_cmd="wildfly14_status"

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

wildfly14_start ()
{
	if [ ! -d "${wildfly14_logdir}" ]
	then
		install -d -o ${wildfly14_user} ${wildfly14_logdir}
	fi

	echo "wildfly14: making sure all writeable dirs belong to proper user/group"
	chown -R ${wildfly14_user}:${wildfly14_group} ${WILDFLY_HOME}/standalone
	echo "Starting wildfly14."
	daemon -u ${wildfly14_user} ${WILDFLY_HOME}/bin/standalone.sh ${wildfly14_args} >> ${wildfly14_log_stdout} 2>> ${wildfly14_log_stderr}

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

wildfly14_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 "${wildfly14_kill9}" ]
		then
			sleep ${wildfly14_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 "${wildfly14_additional_killall}" ]
		then
			sleep ${wildfly14_sleep}
			killall ${wildfly14_additional_killall}
		fi
		rm ${pidfile}
	fi
}

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

run_rc_command "$1"
