#!/bin/sh
# $FreeBSD: ports/mail/dkimproxy/files/dkimproxy_out.in,v 1.3 2006/09/18 14:15:22 rafan Exp $
#

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

#
# Add the following lines to /etc/rc.conf to enable dkimproxy.out:
#
# dkimproxy_out_enable="YES"
#
# Before you enable dkimproxy.out, you also need to make your domainkey to
# set it to DNS and configurate dkimproxy_out_flags.
#

. %%RC_SUBR%%

name="dkimproxy_out"
rcvar=`set_rcvar`

# set defaults

: ${dkimproxy_out_enable="NO"}
: ${dkimproxy_out_flags="--keyfile=%%PREFIX%%/etc/dkimproxy/private.key \
	--selector=selector1 --domain=example.org --method=relaxed \
	127.0.0.1:10027 127.0.0.1:10028"}
: ${dkimproxy_out_pidfile="/var/run/dkimproxy_out.pid"}
: ${dkimproxy_out_user="dkimproxy"}

start_cmd="dkimproxy_out_start"
stop_cmd="dkimproxy_out_stop"

dkimproxy_out_start()
{
	if [ -f ${dkimproxy_out_pidfile} ]; then
		echo "${name} already running?"
		exit 1
	fi 
	if pw user show "${dkimproxy_out_user}" > /dev/null 2>&1; then else
		echo "dkimproxy_out_user: ${dkimproxy_out_user} not found"
		exit 1
	fi
	echo "Starting ${name}"
	logger -t ${name} "Starting ${name}"
	touch ${dkimproxy_out_pidfile}
	chown ${dkimproxy_out_user} ${dkimproxy_out_pidfile}
	tmpfile=`mktemp /tmp/${name}.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX`
	su -m ${dkimproxy_out_user} -c "daemon -c -p ${dkimproxy_out_pidfile} \
		%%PREFIX%%/bin/dkimproxy.out ${dkimproxy_out_flags}" \
		> /dev/null 2> ${tmpfile}
	# wait until dkimproxy 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 ${dkimproxy_out_pidfile}
	else
		# To prevent DoS attack by dkimproxy_out_user.
		chown root:wheel ${dkimproxy_out_pidfile}
	fi
	rm -f ${tmpfile}
}

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

load_rc_config $name
run_rc_command "$1"


syntax highlighted by Code2HTML, v. 0.9.1