#!/bin/sh

COUNTER_FILE="/tmp/start_cnt_syslogd"

start_counter() {
	# increase boot counter
	START_COUNTER=1
	if [ -f "$COUNTER_FILE" ];
	then
	    read -r START_COUNTER < $COUNTER_FILE
	    START_COUNTER=$((START_COUNTER+1))
	fi
	echo "$START_COUNTER" > $COUNTER_FILE
}

start() {
    # Check the configuration file: if there's no target, don't run the thing.
    if ! grep -q '^##.*remote-host' /etc/rsyslog.conf -a
       ! grep -q '^##$outchannel' /etc/rsyslog.conf; then
	echo -n "Starting rsyslog: "
	start-stop-daemon -q -p /var/run/rsyslogd.pid -S \
		--exec /usr/sbin/rsyslogd
	ret=$?
	if [ $ret -eq 0 ]; then
	    start_counter
	    echo "OK"
	elif [ $ret -eq 1 ]; then
	    echo "Failed (already running?)"
	else
	    echo "Failed"
	fi
    else
	echo "Not starting rsyslog: no target host selected"
	# avoid SNMPd complaints about lack of start counter file
	echo "0" > $COUNTER_FILE
    fi
}

stop() {
    echo -n "Stopping rsyslog: "
    start-stop-daemon -K -q -p /var/run/rsyslogd.pid
    if [ $? -eq 0 ]; then
	echo "OK"
    else
	echo "Failed"
    fi
}

restart() {
    stop
    start
}

case "$1" in
  start)
  	start
	;;
  stop)
  	stop
	;;
  restart|reload)
  	restart
	;;
  *)
	echo $"Usage: $0 {start|stop|restart}"
	exit 1
	;;
esac
