#! /bin/sh
#
# $NetBSD: cassandra.sh,v 1.2 2010/10/17 23:41:12 tonnerre Exp $
#
# PROVIDE: cassandra
# REQUIRE: DAEMON
#

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

name="cassandra"
rcvar=$name
command="/usr/pkg/share/cassandra/bin/cassandra"
pidfile="/var/run/cassandra/cassandra.pid"
cassandra_user="cassandra"
cassandra_group="cassandra"
start_cmd="$command start"
stop_cmd="$command stop"
restart_cmd="$stop_cmd && $start_cmd"
run_cmd="cassandra_run"
version_cmd="cassandra_version"
debug_cmd="cassandra_debug"
extra_commands="run version debug"
start_precmd="cassandra_precmd"

PREFIX=/usr/pkg

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

CATALINA_HOME=/usr/pkg/share/cassandra
CASSANDRA_HOME=/usr/pkg/share/cassandra
CASSANDRA_CONF=/usr/pkg/etc/cassandra
CATALINA_PID=${pidfile}
export CATALINA_HOME
export CASSANDRA_HOME
export CASSANDRA_CONF
export CATALINA_PID

find ${PREFIX}/lib -type f -name \*.jar -print | while read jar
do
	CLASSPATH=${CLASSPATH}:${jar}
done
unset jar

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

cassandra_precmd()
{
	if [ ! -d /var/run/cassandra ]; then
		/bin/mkdir -p /var/run/cassandra
		/bin/chmod 0750 /var/run/cassandra
		/usr/sbin/chown ${cassandra_user}:${cassandra_group} /var/run/cassandra
	fi
}

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

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


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

cassandra_version()
{
	/usr/bin/su ${cassandra_user} -c "${command} version"
}

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

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