#!/bin/sh

# PROVIDE: pksd
# REQUIRE: DAEMON
# KEYWORD: SHUTDOWN
#
# Add the following lines to /etc/rc.conf.local or /etc/rc.conf
# to enable this service:
#
# pksd_enable (bool):		Set to NO by default.
#				Set it to YES to enable pksd.
#
# pksd_config (path):		Set to /usr/local/etc/pksd.conf
#				by default.
#
# pksd_mailq_enable (bool):     Set to NO by default. Process incoming
#                               mail queue of commands and key requests
#                               (you will need to configure your mail
#                               infrastructure to enable this. See:
#                               /usr/local/share/doc/pks/README and
#                               /usr/local/share/doc/pks/EMAIL for details.
# 
# pksd_queue_delay (int):       Periodically process incoming mail.
#				Set to 60 seconds by default.

. /etc/rc.subr

name="pksd"
rcvar=pksd_enable

load_rc_config $name

: ${pksd_enable:="NO"}
: ${pksd_mailq_enable:="NO"}
: ${pksd_config="/usr/local/etc/pksd.conf"}
: ${pksd_queue_delay="60"}

command="/usr/local/sbin/${name}"
command_args="/usr/local/etc/${name}.conf"
required_files="${pksd_config}"
start_precmd="${name}_precmd"
start_cmd="${name}_start"
#start_postcmd="${name}_runqueue"
stop_command="${name}_clean_stop"
pidfile="/var/run/${name}.pid"

pksd_precmd()
{
	if [ ! -f /usr/local/etc/${name}.conf ]
        then
                exit 0
        else
                dbdir=`awk '/db_dir/ { print $2 }' < /usr/local/etc/${name}.conf`
        fi
        if [ ! -f ${dbdir}/keydb000 -a -x /usr/local/bin/pksclient ]
        then
                /usr/local/bin/pksclient ${dbdir} create
	fi
}

pksd_start()
{
	echo "Starting pksd"
        /usr/sbin/daemon -f -p ${pidfile} ${command} ${command_args}
}

pksd_runqueue()
{
	if [ -x /usr/local/bin/${name}ctl -a -x /usr/local/bin/pks-queue-run.sh ] && checkyesno pksd_mailq_enable
        then
        	echo "Doing queue run for ${name} every ${pksd_queue_delay} seconds."
	        sleep 2
        	/usr/local/bin/pks-queue-run.sh /usr/local/etc/${name}.conf ${pksd_queue_delay}
  fi
}

pksd_clean_stop()
{
        if [ ! -f /usr/local/etc/${name}.conf ]
        then
                exit 0
        else
                socket=`awk '/socket_name/ { print $2 }' < /usr/local/etc/${name}.conf`
        fi
        if [ -x /usr/local/bin/${name}ctl -a -S ${socket} ]
        then
                echo "Shutting down ${name} socket connections using pksdctl."
                /usr/local/bin/${name}ctl ${socket} shutdown
        else
                echo "couldn't stop ${name}."
        fi
}


load_rc_config $name
run_rc_command "$1"
