#!/bin/sh

# PROVIDE: dkfilter_in
# REQUIRE: LOGIN
# BEFORE: mail
# KEYWORD: shutdown

#
# Add the following lines to /etc/rc.conf to enable dkfilter.in:
#
# dkfilter_in_enable="YES"
#

. /etc/rc.subr

name=dkfilter_in
rcvar=dkfilter_in_enable

# set defaults

: ${dkfilter_in_enable="NO"}
: ${dkfilter_in_flags="127.0.0.1:10025 127.0.0.1:10026"}
: ${dkfilter_in_pidfile="/var/run/dkfilter_in.pid"}
: ${dkfilter_in_user="dkfilter"}

start_cmd="dkfilter_in_start"
stop_cmd="dkfilter_in_stop"

dkfilter_in_start()
{
	if [ -f ${dkfilter_in_pidfile} ]; then
		echo "${name} already running?"
		exit 1
	fi
	echo "Starting ${name}."
	logger -t ${name} "Starting ${name}"
	tmpfile=`mktemp /tmp/dkfilter.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX`
	touch ${dkfilter_in_pidfile}
	chown ${dkfilter_in_user} ${dkfilter_in_pidfile}
	su -m ${dkfilter_in_user} -c "daemon -p ${dkfilter_in_pidfile} \
		%%PREFIX%%/bin/dkfilter.in ${dkfilter_in_flags}" \
		> /dev/null 2> ${tmpfile}
	# wait until dkfilter start.
	while true
	do
		filesize=`ls -l $tmpfile|awk '{print $5}'`
		if [ ${filesize} -gt 0 ]; then
			break
		fi
	done

	logger -t ${name} `cat ${tmpfile}`
	err=`grep Error ${tmpfile}`
	if [ "${err}" ]; then
		echo "Failed to start ${name}."
		echo "${err}"
		rm -f ${dkfilter_in_pidfile}
	else
		# To prevent DoS attack by dkfilter_in_user.
		chown root:wheel ${dkfilter_in_pidfile}
	fi
	rm -f ${tmpfile}
}

dkfilter_in_stop()
{
	if [ ! -f ${dkfilter_in_pidfile} ]; then
		echo "${name} not running?"
		exit 1
	fi
	kill `cat ${dkfilter_in_pidfile}`
	rm -f ${dkfilter_in_pidfile}
	echo "Stopping ${name}"
}

load_rc_config $name
run_rc_command "$1"
