#! /bin/sh
#
# $NetBSD: jetty.sh,v 1.1 2015/12/14 13:05:30 jperkin Exp $
#
# PROVIDE: jetty
# REQUIRE: DAEMON
#

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

name="jetty"
rcvar=$name
command="/usr/pkg/share/jetty/bin/jetty.sh"
pidfile="jetty.pid"
jetty_user="jetty"
jetty_group="jetty"
start_cmd="$command start"
stop_cmd="$command stop"
restart_cmd="$stop_cmd && $start_cmd"
run_cmd="jetty_run"
version_cmd="jetty_version"
debug_cmd="jetty_debug"
extra_commands="run version debug"
start_precmd="jetty_precmd"

PREFIX=/usr/pkg

JAVA_OPTIONS="-Xmx768M -Djava.nio.channels.spi.SelectorProvider=sun.nio.ch .PollSelectorProvider"

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

JETTY_HOME=/usr/pkg/share/jetty
JETTY_BASE=/var/jetty
JETTY_LOGS=/var/jetty/logs
JETTY_RUN=/var/jetty
JETTY_PID=${pidfile}
export JETTY_HOME
export JETTY_BASE
export JETTY_LOGS
export JETTY_RUN
export JETTY_PID

CLASSPATH=${CLASSPATH}:${PREFIX}/lib/java/servlet.jar:${PREFIX}/lib/java/jaxp.jar:${PREFIX}/lib/java/parser.jar:${PREFIX}/lib/java/crimson.jar:${PREFIX}/lib/java/ant.jar

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

jetty_precmd()
{
	if [ ! -d ${JETTY_RUN} ]; then
		/bin/mkdir -p ${JETTY_RUN}
		/bin/chmod 0750 ${JETTY_RUN}
		/usr/sbin/chown ${jetty_user}:${jetty_group} ${JETTY_RUN}
	fi
}

jetty_start()
{
	cd ${JETTY_HOME}/logs
	/usr/bin/su ${jetty_user} -c "${command} start"
}

jetty_stop()
{
	rc_pid=$(check_pidfile ${JETTY_RUN}/${JETTY_PID} "${JAVA_HOME}/bin/java")
	/usr/bin/su ${jetty_user} -c "${command} stop"
	wait_for_pids $rc_pid
}

jetty_run()
{
	cd ${JETTY_HOME}/logs
	/usr/bin/su ${jetty_user} -c "${command} run"
}

if [ -f /etc/rc.subr ]; then
	load_rc_config "$name"
	run_rc_command "$1"
else
	jetty_precmd
	jetty_start
fi
