#!/bin/sh

# PROVIDE: kafka
# REQUIRE: NETWORKING SERVERS DAEMON
# KEYWORD: shutdown
#
# Add kafka_enable="YES" to /etc/rc.conf to enable Kafka:
#
# Additional variables you can define are:
#
# kafka_user:				Username to run Kafka
#					Default: %%KAFKA_USER%%
# kafka_group:				Group to run Kafka
#					Default: %%KAFKA_GROUP%%
# kafka_config:				Configuration file to run Kafka
#					Default: %%ETCDIR%%/server.properties
# kafka_log4j_config:			Configuration file for Kafka logging
#					Default: %%ETCDIR%%/log4j.properties
# kafka_log_dir:			Directory to store Kafka logs
#					Default: %%KAFKA_LOGDIR%%
# kafka_java_opts:			Options passed to JVM to start Kafka
#					Default: None
# kafka_pidfile:			Full path of the Kafka process PID file
#					Default: /var/run/kafka.pid
# kafka_syslog_output_enable:		Set to enable syslog output.
#					Default: YES
# kafka_syslog_output_tag:		Set syslog tag if syslog enabled.
#					Default: kafka
# kafka_syslog_output_priority:		Set syslog priority if syslog enabled.
#					Default: info
# kafka_syslog_output_facility:		Set syslog facility if syslog enabled.
#					Default: daemon

. /etc/rc.subr

name=kafka
rcvar=kafka_enable

load_rc_config "${name}"

: ${kafka_enable:="NO"}
: ${kafka_user:="%%KAFKA_USER%%"}
: ${kafka_group:="%%KAFKA_GROUP%%"}
: ${kafka_config:="%%ETCDIR%%/server.properties"}
: ${kafka_log4j_config:="%%ETCDIR%%/log4j.properties"}
: ${kafka_log_dir:="%%KAFKA_LOGDIR%%"}
: ${kafka_pidfile:=/var/run/kafka.pid}
: ${kafka_syslog_output_enable:="YES"}

start_precmd="kafka_start_precmd"

# backwards compatibility
if [ -n "${kafka_log4j_profile}" ]; then
	kafka_log4j_config="${kafka_log4j_profile#file:}"
fi

if checkyesno kafka_syslog_output_enable; then
	if [ -n "${kafka_syslog_output_tag}" ]; then
		kafka_syslog_output_flags="-T ${kafka_syslog_output_tag}"
	else
		kafka_syslog_output_flags="-T ${name}"
	fi
	if [ -n "${kafka_syslog_output_priority}" ]; then
		kafka_syslog_output_flags="${kafka_syslog_output_flags} -s ${kafka_syslog_output_priority}"
	fi
	if [ -n "${kafka_syslog_output_facility}" ]; then
		kafka_syslog_output_flags="${kafka_syslog_output_flags} -l ${kafka_syslog_output_facility}"
	fi
fi

JAVA="%%JAVA%%"
CLASSPATH=":%%DATADIR%%/libs/*"

kafka_class="kafka.Kafka"
kafka_log_opts="-Dkafka.logs.dir=${kafka_log_dir} -Dlog4j.configuration=file:${kafka_log4j_config}"
kafka_main="${kafka_java_opts} ${kafka_log_opts} -cp ${CLASSPATH} ${kafka_class} ${kafka_config}"
pidfile="${kafka_pidfile}"
required_dirs="${kafka_log_dir}"
required_files="${kafka_config} ${kafka_log4j_config}"

command="/usr/sbin/daemon"
command_args="-f ${kafka_syslog_output_flags} -P ${pidfile} -t ${name} ${JAVA} ${kafka_main}"

kafka_start_precmd()
{
	if [ ! -e "${pidfile}" ]; then
		install -m 0600 -o "${kafka_user}" -g "${kafka_group}" /dev/null "${pidfile}"
	fi
}

run_rc_command "$1"
