#!/bin/sh
#
# mailgraph	This shell script takes care of starting and stopping
#		mailgraph service.
#
# chkconfig:	345 55 45
# description:	mailgraph watches postfix logfiles and generates www statistics

# Source function library.
. /etc/rc.d/init.d/functions

MAILGRAPH_CONFIG=/etc/mailgraph.conf
DAEMON=/usr/sbin/mailgraph.pl
PID_FILE=/var/run/mailgraph/mailgraph.pid
RRD_DIR=/var/lib/mailgraph
MAIL_LOG=/var/log/maillog

[ -f "$MAILGRAPH_CONFIG" ] && source $MAILGRAPH_CONFIG

ARGS="-l $MAIL_LOG -d --daemon_rrd=$RRD_DIR --daemon_pid=/var/run/mailgraph/mailgraph.pid --daemon_log=/var/lib/mailgraph/mailgraph.log -v"

# See how we were called.
case "$1" in
  start)
	# Check if the service is already running?
	if [ ! -f /var/lock/subsys/mailgraph ]; then
		echo -n "Starting Postfix Mail Statistics: "
		daemon --user mailgraph +10 /usr/sbin/mailgraph.pl $ARGS
		sleep 1
		ps -C mailgraph >/dev/null 2>&1
		RETVAL=$?
		CPID=$!
		if [ $RETVAL -eq 0 ]; then
			touch /var/lock/subsys/mailgraph
			echo $CPID > $PID_FILE
			echo
		fi
	else
		echo "already running"
		exit 1
	fi

        ;;
  stop)
        if [ -f /var/lock/subsys/mailgraph ]; then
        	echo -n "Stopping Postfix Mail Statistics: "
        	killproc mailgraph
        	rm -f /var/lock/subsys/mailgraph >/dev/null 2>&1
        	rm -f $PID_FILE >/dev/null 2>&1
		echo
        else
	        echo "mailgraph not running"
                exit 1
        fi
															
        ;;
  status)
  	status mailgraph
	exit $?
	;;
  condstop)
  	if [ -f /var/lock/subsys/mailgraph ]; then
		stop
	fi
	;;
  condstart)
  	if [ ! -f /var/lock/subsys/mailgraph ]; then
		start
	fi
	;;
  condrestart)
  	if [ -f /var/lock/subsys/mailgraph ]; then
		restart
	fi
	;;
  restart)
	$0 stop
	$0 start
	;;
  *)
        echo "Usage: $0 {start|stop|status|restart}"
        exit 1
esac

exit $RETVAL
