#!/bin/sh

### BEGIN INIT INFO
# Provides:		knoerred
# Required-Start:	$network
# Required-Stop:	$network
# Default-Start:	2 3 4 5
# Default-Stop:		0 1 6
# Short-Description:	Start knoerred at boot time
# Description:		knoerred is a remote monitoring daemon of the
#			ngtx package
### END INIT INFO

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/bin/knoerred
KNOERRED_PORT=8889
KNOERRED_ALLOWED_ADDRESSES="127.0.0.1"
DAEMONIZEP=/usr/bin/daemonizep
NAME=knoerred
DESC=knoerred

test -e $DAEMON || exit 1
test -e $DAEMONIZEP || exit 1

test -f /lib/lsb/init-functions || exit 1
. /lib/lsb/init-functions


# Include knoerred defaults if available
if [ -f /etc/default/knoerred ]; then
	. /etc/default/knoerred
fi
DAEMON_OPTS="$KNOERRED_PORT $KNOERRED_ALLOWED_ADDRESSES"

set -e

case "$1" in
	start)
		echo -n "Starting $DESC: "
		if status_of_proc "$DAEMON" $DESC > /dev/null; then
			log_begin_msg "Already running."
		else
			#start-stop-daemon --start --quiet --exec $DAEMON -- $DAEMON_OPTS
			$DAEMONIZEP $DAEMON $DAEMON_OPTS >/var/run/$NAME || \
				log_failure_msg "failed to start $NAME"
			echo "$NAME."
		fi
		;;

	stop)
		echo -n "Stopping $DESC: "
		start-stop-daemon --stop --oknodo --quiet --user root --exec $DAEMON
		echo "$NAME."
		;;

	restart|force-reload)
		echo -n "Restarting $DESC: "
		start-stop-daemon --stop --oknodo --quiet --user root --exec $DAEMON
		sleep 1
		start-stop-daemon --start --quiet --exec $DAEMON -- $DAEMON_OPTS
		echo "$NAME."
		;;

	status)
		start-stop-daemon --test --stop --quiet --user root --exec $DAEMON && \
			log_success_msg "$NAME daemon is running." || \
			( log_failure_msg "$NAME daemon is NOT running" && exit 1 )
		;;		

	check)
		$DAEMON $DAEMON_OPTS "-n"
		;;

	*)
		N=/etc/init.d/$NAME
		echo "Usage: $N {start|stop|restart|force-reload|status|check}" >&2
		exit 1
		;;
esac

exit 0
