#!/usr/bin/bash
# 
# chkconfig: 345 99 01
# description: opmonstats tool
#
#
#set -x

. /etc/rc.d/init.d/functions

stop () {

	echo -n "Stopping opmonstats"
	PID=`cat $PIDFILE 2>/dev/null`
	PID=`/bin/echo -n $PID`
	RUNNING=`/bin/ps $PID | /bin/grep opmonstats.php | /usr/bin/wc -l`
	if [ $RUNNING -lt 1 ]; then
		echo "   opmonstats currently stopped"
		if [ $EXITONPREMATUREFAIL -eq 1 ]; then
			exit 0
		fi

		return 0
	fi

	/bin/kill -9 $PID 2>/dev/null
	C=0
	while [ $RUNNING -ge 1 -a $C -lt 12 ]
	do
		echo -n .
		/bin/sleep 1
		C=`expr $C + 1`
		RUNNING=`/bin/ps $PID | /bin/grep opmonstats | /usr/bin/wc -l`
	done

	if [ $RUNNING -ge 1 ]; then
		echo " fail... unable to stop opmonstats process"
		if [ $EXITONPREMATUREFAIL -eq 1 ]; then
			exit 1
		fi

		return 1
	fi

	echo " success"
}

start () {
	PID=`cat $PIDFILE 2>/dev/null`
	PID=`/bin/echo -n $PID`
	RUNNING=`/bin/ps $PID | /bin/grep opmonstats.php | /usr/bin/wc -l`
	if [ $RUNNING -ge 1 ]
	then
		echo "FAIL: opmonstats already running. stop it first and try again"
		exit 0
	fi

	/usr/local/opmon/bin/opmonstats.php 
	exit 0
}

PIDFILE=/var/run/opmonstats.pid
EXITONPREMATUREFAIL=1
case "$1" in

	start)
		start;
		;;

	stop)
		stop;
		;;

	restart)
		EXITONPREMATUREFAIL=0
		stop;
		if [ $? -ne 0 ]; then
			exit
		fi
		start;
		;;

	status)
		status opmonstats.php
		exit $?
		;;

	*)
		echo "Usage: opmonstats {start|stop|restart|status}"
		exit 1
		;;

esac
