#!/bin/sh
#
# jboss72 startup script.
#
# $FreeBSD: head/java/jboss72/files/jboss72.in 317332 2013-05-04 18:27:34Z crees $
#

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

# Add the following lines to /etc/rc.conf to enable jboss72:
# jboss72_enable (bool):      Set to "YES" to enable jboss72
# jboss72_jvm_opts (str):     Extra JVM flags.
# jboss72_args (str):         Optional arguments to JBoss
# jboss72_logging (str)       JBoss log output. A pipe command may be used.
#

. /etc/rc.subr

name="jboss72"
rcvar=jboss72_enable

load_rc_config $name

jboss72_enable="${jboss72_enable:-"NO"}"
jboss72_logging="${jboss72_logging:-">> ${jboss72_logdir}/stdout.log 2>> ${jboss72_logdir}/stderr.log"}"
jboss72_sleep="${jboss72_sleep:-"5"}"
jboss72_kill9="${jboss72_kill9:-""}"
jboss72_additional_killall="${jboss72_additional_killall:-""}"
jboss72_user="www"
jboss72_logdir="/var/log/jboss72"

start_cmd="jboss72_start"
stop_cmd="jboss72_stop"
pidfile="/var/run/jboss72.pid"

JBOSS_HOME="/usr/local/jboss-as-7.2.0.Final"

jboss72_start ()
{
	if [ ! -d "${jboss72_logdir}" ]
	then
		install -d -o ${jboss72_user} ${jboss72_logdir}
	fi

	echo "Starting jboss72."
	daemon -u ${jboss72_user} ${JBOSS_HOME}/bin/standalone.sh ${jboss72_logging} >> ${jboss72_logdir}/boot.log 2>> ${jboss72_logdir}/boot.log

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

jboss72_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 "${jboss72_kill9}" ]
		then
			sleep ${jboss72_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 "${jboss72_additional_killall}" ]
		then
			sleep ${jboss72_sleep}
			killall ${jboss72_additional_killall}
		fi
	fi
}

run_rc_command "$1"
