#!/bin/sh
#
# ::copy::
# ::maintainer::
#
set -e

SVCNAME="ku-daemontools"
DESC="[ku] DJB Daemontools"
DAEMON="/usr/bin/svscanboot"
DAEMONNAME="svscanboot"

defaults="/etc/default/$SVCNAME"
pidfile="/var/run/$SVCNAME.pid"

# init options (from /etc/default file)
#
KU_DAEMONTOOLS_ENABLE="true"
KU_DAEMONTOOLS_OPTS=""
KU_DAEMONTOOLS_NICE=""

test -x $DAEMON || exit 0

. /lib/lsb/init-functions
. /etc/default/rcS

[ -s $defaults ] && . $defaults


# sanity checks and set local vars
#
extraopts="$KU_DAEMONTOOLS_OPTS"


enabled=
case "x$KU_DAEMONTOOLS_ENABLE" in
  xtrue|xfalse)
  	enabled=$KU_DAEMONTOOLS_ENABLE
  	;;
  *)	log_failure_msg "$defaults: KU_DAEMONTOOLS_ENABLE accept true or false"
	log_failure_msg "not starting $SVCNAME daemon"
	exit 1
	;;
esac


nicelevel=
case "x$KU_DAEMONTOOLS_NICE" in
  x[0-9]|x[1-9][0-9])
  	nicelevel="--nicelevel $KU_DAEMONTOOLS_NICE";;
  x)	;;
  *)	log_warning_msg "$defaults: KU_DAEMONTOOLS_NICE must be a value between 0 and 19 (inclusive)"
	log_warning_msg "ignoring KU_DAEMONTOOLS_NICE"
	;;
esac


export PATH="${PATH:+$PATH:}/usr/sbin:/sbin"

do_start()
{
	$enabled || return 0

        log_daemon_msg "Starting $DESC:" "$DAEMONNAME"
        if start-stop-daemon --start --quiet --background \
                --pidfile $pidfile --make-pidfile \
                $nicelevel --exec $DAEMON \
                -- $extraopts
        then
        	rc=0
                sleep 1
                is_running || {
                	log_failure_msg "$DAEMONNAME daemon failed to start"
                	rc=1
                }
	else
                rc=1
	fi
	if [ $rc -eq 0 ]; then
                log_end_msg 0
	else
                log_end_msg 1
                rm -f $pidfile
	fi
}


do_stop()
{
	if is_running
	then
        	log_daemon_msg "stopping $DESC:" "$DAEMONNAME"
		start-stop-daemon --stop --quiet --oknodo --pidfile $pidfile
        	log_end_msg $?
	else
		log_warning_msg "daemon $DAEMONNAME is not running"
		return 0
	fi

	retry=5
	while [ $retry -gt 0 ]
	do
		ps -C $DAEMONNAME >/dev/null 2>/dev/null || break
		retry=`expr $retry - 1`
		sleep 1
	done
	ps -C $DAEMONNAME >/dev/null 2>/dev/null && {
		kill `cat $pidfile`
		sleep 1
	}
	ps -C $DAEMONNAME >/dev/null 2>/dev/null && {
		kill `cat -9 $pidfile`
		sleep 1
	}
	rm -f $pidfile
}



is_running()
{
	if [ -f $pidfile ]
	then
		kill -0 $(cat $pidfile) >/dev/null 2>&1
	else
		return 1
	fi
}


case "$1" in
  start)	do_start ;;
  stop)		do_stop ;;
  restart)
  	do_stop
	do_start
	;;
  reload|force-reload)
        #log_warning_msg "Reloading $DAEMONNAME daemon: not needed, as the daemon re-reads the configs every run"
	do_stop
	do_start
	;;
  status)
	if is_running
	then
		echo "$DAEMONNAME is running"
		ps -C $DAEMONNAME
	else
		echo "$DAEMONNAME is not running"
	fi
	;;
  *)
	echo "usage: $0 {start|stop|reload|force-reload|restart|status}"
	exit 1
esac

exit 0
