#!/bin/sh
#
# Copyright 2003 Meru Networks
# All rights reserved.
#
PROC=/opt/meru/bin/lmgrd
VENDOR_DAEMON=merud

# give lmgrd a bit more time than usual .2 - needs to start/exit the main thread and spawn the work process
START_DELAY=1

MNAME=`basename $PROC`
PIDFILE=/opt/wlan/var/run/${MNAME}.pid
LOG=/opt/wlan/var/log/${MNAME}.log
LICDIR=/opt/meru/licenses

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

start() {

    vrfy_combo `cat $PIDFILE 2>/dev/null` && {
        return
    }

    vrfy $PROC || {
        # if it reaches here, then lmgrd is not running
        vrfy $VENDOR_DAEMON && {
            # though lmgrd is not running "merud" is running
            warning "$VENDOR_DAEMON killed before starting $MNAME."
            pkill -9 -f $VENDOR_DAEMON 2>/dev/null
        }
    }

    echo "============ $0 start =================" >> $LOG
    cd /opt/wlan/etc

    $PROC -local -x lmremove -c $LICDIR >> $LOG 2>&1 &
    sleep $START_DELAY
    # Using the common writePO_pid to create a PID file
    writeP1_pid
    
    vrfy `cat $PIDFILE 2>/dev/null` || {
        warning "$PROC did not start. Will try again."
    }
}

stop() {
	/opt/meru/bin/lmdown -all 

	monit_stop_process
}

case "$1" in
	start)
		set_params
		if vrfy monit; then
			start_with_monit $MNAME
		else
			start
		fi
		;;
	stop)
		if vrfy monit; then
                        stop_with_monit $MNAME
		else
			stop
		fi
		;;
	restart)
		if vrfy monit; then
                        restart_with_monit $MNAME
		else
			stop
			start
		fi
		;;
	mstart)
		set_params
		start
		;;
	mstop)
		stop
		;;
	*)
		echo $"Usage: $prog {start|stop|restart}"
		exit 1
esac

exit 0
