#! /bin/sh
#
# $NetBSD: tomcat.sh,v 1.2 2020/04/25 22:23:05 jym Exp $
#
# PROVIDE: tomcat
# REQUIRE: DAEMON
#

if [ -r /etc/rc.subr ]
then
	. /etc/rc.subr
fi

name="tomcat"
rcvar=$name
command="/usr/pkg/share/tomcat/bin/catalina.sh"
pidfile="/var/run/tomcat/catalina.pid"
tomcat_user="tomcat"
tomcat_group="tomcat"
start_cmd="tomcat_start"
stop_cmd="tomcat_stop"
restart_cmd="$stop_cmd && $start_cmd"
run_cmd="tomcat_run"
version_cmd="tomcat_version"
debug_cmd="tomcat_debug"
extra_commands="run version debug"
start_precmd="tomcat_precmd"

PREFIX=/usr/pkg

if [ -z "${JAVA_HOME}" ]
then
	JAVA_HOME="/usr/pkg/java/openjdk17"
	export JAVA_HOME
fi

CATALINA_HOME=/usr/pkg/share/tomcat
TOMCAT_HOME=/usr/pkg/share/tomcat
CATALINA_PID=${pidfile}
export CATALINA_HOME
export TOMCAT_HOME
export CATALINA_PID

if [ -n "${tomcat_classpath}" ]
then
	CLASSPATH=${CLASSPATH}:${tomcat_classpath}
fi
export CLASSPATH

tomcat_precmd()
{
	if [ ! -d /var/run/tomcat ]; then
		/bin/mkdir -p /var/run/tomcat
		/bin/chmod 0750 /var/run/tomcat
		/usr/sbin/chown ${tomcat_user}:${tomcat_group} /var/run/tomcat
	fi
}

tomcat_start()
{
	cd $CATALINA_HOME/logs
	/usr/bin/su ${tomcat_user} -c "${command} start"
}

tomcat_stop()
{
	rc_pid=$(check_pidfile $pidfile "${JAVA_HOME}/bin/java")
	/usr/bin/su ${tomcat_user} -c "${command} stop"
	wait_for_pids $rc_pid
}


tomcat_run()
{
	cd ${CATALINA_HOME}/logs
	/usr/bin/su ${tomcat_user} -c "${command} run"
}

tomcat_version()
{
	/usr/bin/su ${tomcat_user} -c "${command} version"
}

tomcat_debug()
{
	cd ${CATALINA_HOME}/logs
	/usr/bin/su ${tomcat_user} -c "${command} debug"
}

if [ -f /etc/rc.subr ]
then
	load_rc_config "$name"
	run_rc_command "$1"
else
	echo -n ' ${name}'
	exec ${command} ${tomcat_flags} ${command_args}
fi
