#!/bin/sh
# Start/stop the MRTG
# Original author:    Stefan SF <stefan@sf-net.com> (for Fedora Project)
# Updates for Debian: Joao Eriberto Mota Filho <eriberto@debian.org>
#
### BEGIN INIT INFO
# Provides: mrtg
# Required-Start: $network
# Required-Stop: $network
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: Starts the The Multi Router Traffic Grapher
# Description: The Multi Router Traffic Grapher is a tool primarily used to
#              monitor the traffic load on network links (typically by using
#              SNMP). MRTG generates HTML pages containing PNG images which
#              provide a LIVE visual representation of this traffic. MRTG
#              typically produces daily, weekly, monthly, and yearly graphs.
### END INIT INFO

# source function library
. /lib/lsb/init-functions

MRTG="/usr/bin/mrtg"
USERMRTG="mrtg"
CONFIG="/etc/mrtg/mrtg.cfg"
PIDFILE="/run/mrtg/mrtg.pid"
OPTIONS="--daemon --fhs --user=${USERMRTG}"

RETVAL=0

start() {
	if [ ! -e $PIDFILE ]
	then
	    WORKDIR=$(cat ${CONFIG} | grep -i WorkDir | cut -d: -f2 | tr -d " ")
	    if [ -z ${WORKDIR} ]
	    then
		echo "ERROR: WorkDir not defined in config file"
		exit 1
	    fi
	    if [ ! -d ${WORKDIR} ]
	    then
		echo "ERROR: no such directory: ${WORKDIR}"
		exit 1
	    fi
	    OWNERWORKDIR=$(stat -c '%U' ${WORKDIR})
	    if [ ${OWNERWORKDIR} != ${USERMRTG} ]
	    then
		echo "ERROR: ${WORKDIR} is not owned by ${USERMRTG}"
		exit 1
	    fi
	    echo "Starting MRTG"
	    LANG=C ${MRTG} ${OPTIONS} ${CONFIG}
	    RETVAL=$?
	else
	    echo "MRTG is already running"
	    RETVAL=$?
	fi
}

stop() {
	if [  -e $PIDFILE ]
	then
	    echo "Stopping MRTG"
	    kill `cat ${PIDFILE}`
	    RETVAL=$?
	else
	    echo "MRTG is not running"
	    RETVAL=$?
	fi
}

restart() {
	stop
	sleep 1
	start
}

case "$1" in
  start)
	start
	;;
  stop)
	stop
	;;
  restart|force-reload)
	restart
	;;
  status)
	if [ -e $PIDFILE ]; then
		echo "MRTG is enabled"
		RETVAL=0
	else
		echo "MRTG is disabled"
		RETVAL=3
	fi
	;;
  *)
	echo "Usage: $0 {start|stop|status|restart|force-reload}"
	exit 1
esac

exit $RETVAL
