#! /bin/sh
#
# monit         Monitors processes and restarts them if they exit
#

PATH=/opt/meru/bin:/usr/local/sbin:/sbin:/usr/sbin:/usr/local/bin:/bin:/usr/bin
export PATH

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

RETVAL=0
MONIT_RESTART_COUNT=0

PROC=/opt/meru/bin/monit
MNAME=`basename $PROC`
PIDFILE=/var/run/${MNAME}.pid
CONF=/opt/wlan/etc/${MNAME}.conf
LOG=/opt/wlan/var/log/${MNAME}.log

[ -f $PROC ] || exit 0

if [ -f /etc/init.d/meru-functions ]; then
	. /etc/init.d/meru-functions
else
	echo "/etc/init.d/meru-functions must exist to use $0"; exit 1
fi

# See how we were called.
case "$1" in
  init)
	while [ "`pgrep -f $PROC`" ]; do

		# monit should NOT be running at this point, make sure...
		if [ $MONIT_RESTART_COUNT -gt 5 ]; then
			echo "WARNING: could not restart $MNAME!" >> /dev/ttyS0
			exit -1
		fi

		echo [`date`] Old $MNAME process still running, attempting to kill it... >> $LOG 
		pkill -9 -f $PROC 
		sleep 2
		MONIT_RESTART_COUNT=$(($MONIT_RESTART_COUNT+1))
	done

	echo [`date`] INIT calls monit. >> $LOG

	# Prevent from showing the comment on running time 
	#echo -n "Initialize $MNAME: "
	$PROC -c $CONF -l $LOG -d 5
	sleep 2
	;;
	
  start)
	echo -n "Starting $MNAME: "
	# kill monit to respawn by INIT kernel 
	pkill -9 -f $PROC 
	RETVAL=$?

	[ $RETVAL -eq 0 ] && {
		echo "[OK]"
		touch /var/lock/subsys/monit
	}
	;;
  stop)
	echo -n "Stopping $MNAME: "
	# stop monit to avoid respawn by INIT kernel 
	pkill -19 -f $PROC 
	RETVAL=$?

	[ $RETVAL -eq 0 ] && {
		echo "[OK]"
		rm -f /var/lock/subsys/monit
	}
	;;
  status)
	status $MNAME 
	RETVAL=$?
	;;
  restart)
	# kill monit and then INIT kernel spawns monit in inittab
	pkill -9 $MNAME 
	RETVAL=$?
	;;
  reload)
	killall -HUP $MNAME 
	RETVAL=$?
	;;
  mstart)
        # kill monit to respawn by INIT kernel
        pkill -9 -f $PROC >/dev/null 2>&1
	;;
  mstop)
        # let monit respawn by INIT kernel
	;;
  *)
	echo "Usage: inet {start|stop|status|restart|reload|mstart|mstop}"
	exit 1
esac

exit $RETVAL
