#!/bin/sh -e

# $Id: init,v 1.2 1998/04/04 05:00:34 roderick Exp $

script=`basename "$0"`

daemon=/usr/sbin/mon
cfg=/etc/mon.cf
pid=/var/run/mon/mon.pid
desc='monitor daemon'
name=mon

# Add system dirs for start-stop-daemon.
PATH=$PATH:/sbin:/usr/sbin

[ -f $daemon -a -f $cfg ] || exit 0

# Don't bother if the user hasn't configured the package, there is no
# default configuration but there is a default config file (which just
# contains comments).

egrep -v '^[ 	]*$|^#' $cfg >/dev/null || exit 0

warn() {
    echo "$script:" "$@" >&2
}

die() {
    warn "$@"
    exit 1
}

usage() {
    [ $# = 0 ] || warn "$@"
    warn "usage: \`$script -<action>'"
    warn "valid actions: start stop restart reload force-reload"
    exit 1
}

# I originally used su to start the daemon as user daemon, but ran into
# trouble with the differing requirements of su and secure-su.  The GNU
# getopt's troublsome behavior of looking for switches anywhere on the
# command line requires that one use -- if one wants to pass switches
# to the shell, but secure-su doesn't allow the --.  One could set
# POSIXLY_CORRECT to prevent this poor getopt_long() behavior, but then
# the sub-command would have that in its environment.  In disgust I
# gave up and switched to using Perl.

daemon_run() {
    perl -we '
	$> = $< = $) = $( = 1;
	if ($> != 1 || $< != 1 || $) != 1 || $( != 1) {
	    die "Error setting ids, currently user $</$>, group $(/$)\n";
	}
	exec @ARGV or die "Error running $ARGV[0]: $!\n";
    ' "$@" || die "return $? setting ids to daemon and running:" "$@"
}

[ $# = 1 ] || usage "wrong number of args (got $# expected 1), args are:" "$@"

action=$1
set -- --pidfile $pid --startas $daemon -- -f

case x-$action in
    x-start)
	echo -n "Starting $desc: $name"
	daemon_run start-stop-daemon --start "$@"
	echo .
	;;
    x-stop)
	echo -n "Stopping $desc: $name"
	start-stop-daemon --stop --oknodo --quiet "$@"
	echo .
	;;
    x-restart)
    	echo -n "Restarting $desc: $name"
	start-stop-daemon --stop --oknodo --quiet "$@"
	daemon_run start-stop-daemon --start "$@"
	echo .
	;;
    x-reload | x-force-reload)
	echo "Reloading $desc configuration files."
	start-stop-daemon --stop --signal 1 "$@"
	;;
    *)
    	usage "invalid action \`$action'"
	;;
esac

exit 0
