#!/bin/sh

SNMP_PID=/var/run/snmpd.pid
SNMP_CONF=/etc/snmpd.conf
dotconfig=/wr/etc/dot-config

start_counter() {
	# increase boot counter
	COUNTER_FILE="/tmp/start_cnt_snmpd"
	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() {
    echo -n "Starting snmpd daemon: "

    if [ -f "$dotconfig" ]; then
	. "$dotconfig"
    else
	echo "$0 unable to source dot-config ($dotconfig)!"
    fi

    WRS_LOG=$CONFIG_WRS_LOG_SNMPD

    if [ -z "$WRS_LOG" ]; then
	LOG="";
    elif echo "$WRS_LOG" | grep / > /dev/null; then
        # if a pathname, use it
	LOG="-LF 5 $WRS_LOG";
    else
	# not a pathname: use verbatim
	LOG="-L$WRS_LOG"
    fi

    # Log source address (-a)
    start-stop-daemon -q -p $SNMP_PID -S \
		--exec /usr/sbin/snmpd -- $LOG -p $SNMP_PID -a -c $SNMP_CONF

    ret=$?
    if [ $ret -eq 0 ]; then
	start_counter
	echo "OK"
    elif [ $ret -eq 1 ]; then
	echo "Failed (already running?)"
    else
	echo "Failed"
    fi
}

stop() {
    echo -n "Stopping snmpd: "
    start-stop-daemon -K -q -p $SNMP_PID
    if [ $? -eq 0 ]; then
	echo "OK"
    else
	echo "Failed"
    fi
}

restart() {
    stop
    # give time to snmpd to stop
    sleep 1
    start
}

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