#!/bin/sh
# $Revision: 2 $
# $Date: 2008-09-12 15:11:40 +0300 (Fri, 12 Sep 2008) $
# rc script - *BSD version

CFGFILE=/usr/local/etc/mrtg/mrtg.cfg
MRTGFILE=/usr/local/bin/mrtg
PIDFILE=/usr/local/etc/mrtg/mrtg.pid
LOGFILE=/dev/null
#LOGFILE=/var/log/mrtg.log
LOGDIR=/var/log/mrtg

USAGE='echo "usage: $0 (status|restart|start|stop)"; exit 1'
MRTG="$MRTGFILE $CFGFILE --daemon --logging $LOGFILE"

if [ -f $PIDFILE ]
then
        PID=`cat $PIDFILE`
        PS=`ps $PID | tail -1 | grep $PID`
        RUNNING=1
        [ `echo $PS | wc -w` -ne 0 ] || {
                PS="mrtg (pid $PID?) not running"
                RUNNING=0
        }
else
        PS="mrtg (no pid file) not running"
        RUNNING=0
fi

for ARG
do
        case $ARG in
        start|stop|restart)
                ;;
        *)
                [ $RUNNING -eq 0 ] && {
                        echo $PS
                        exit 1
                }
        esac
        case $ARG in
        start)
                [ $RUNNING -eq 1 ] && {
                        echo "start: mrtg (pid $PID) already running"
                        continue
                }
                if [ ! -d $LOGDIR ]
                then
                    mkdir $LOGDIR
                fi
                $MRTG && echo "start: mrtg started"
                ;;
        stop)
                [ $RUNNING -eq 0 ] && {
                        echo "stop: mrtg not running"
                        continue
                }
                kill $PID && {
                        echo "stop: mrtg (pid $PID) stopped"
                }
                ;;
        restart)
                [ $RUNNING -eq 1 ] && {
                        kill $PID
                        echo "restart: mrtg (pid $PID) stopped"
                }
                $MRTG && echo "restart: mrtg started"
                ;;
        status)
                [ $RUNNING -eq 0 ] && {
                        echo "status: mrtg not running"
                        continue
                }
                [ $RUNNING -eq 1 ] && {
                        echo "status: mrtg is running (pid $PID)"
                        continue
                }
                ;;
        *) eval "$USAGE";;
        esac
done
test -z "$ARG" && eval "$USAGE"
exit 0


