#!/bin/sh
#
# $NetBSD: pksd.sh,v 1.8 2005/10/23 17:45:39 adrianp Exp $
#
# PROVIDE: pksd
# REQUIRE: DAEMON

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

name="pksd"
rcvar=${name}

command="/usr/pkg/bin/pksd"
run_command="/usr/pkg/bin/pks-queue-run.sh"
ctl_command="/usr/pkg/bin/pksdctl"
client_command="/usr/pkg/bin/pksclient"

conf_file="/usr/pkg/etc/${name}.conf"
required_files="${conf_file}"
extra_commands="dbinit"
pksd_user="pks"
pksd_group="pks"

pksd_dbinit()
{
	(
	umask 007
	if [ -r ${conf_file} ]
	then
		dbdir=`/usr/bin/awk '/db_dir/ { print $2 }' < ${conf_file}`
		if [ ! -f ${dbdir}/keydb000 -a -x ${client_command} ]
		then
			/usr/bin/su -m ${pksd_user} -c "${client_command} ${dbdir} create"
		fi
	fi
	)
}

pksd_start()
{
	if [ -r ${conf_file} -a -x ${command} -a -x ${run_command} ]
	then
		echo "Starting ${name} (local)."
		echo "${command} ${conf_file}"
		/usr/bin/su -m ${pksd_user} -c "${command} ${conf_file} &"
		sleep 5
		/usr/bin/su -m ${pksd_user} -c "${run_command} ${conf_file}"
	fi
}

pksd_stop()
{
	if [ -r ${conf_file} -a -x ${ctl_command} ]
	then
		socket=`/usr/bin/awk '/socket_name/ { print $2 }' < ${conf_file}`
		if [ -S ${socket} ]
		then
			echo "Stopping ${name} (local)."
			/usr/bin/su -m ${pksd_user} -c "${ctl_command} ${socket} shutdown"
		fi
	fi
} 

dbinit_cmd=pksd_dbinit
start_precmd=pksd_dbinit
start_cmd=pksd_start
stop_cmd=pksd_stop

if [ -f /etc/rc.subr ]
then
	load_rc_config $name
	run_rc_command "$1"
else
	echo -n " ${name}"
	pksd_dbinit
	pksd_start
fi
