#!/bin/sh
#
# Copyright 2003 Meru Networks
# All rights reserved.
#

PROC=/opt/meru/bin/np1slave
NP1SLAVE_CONF=/opt/wlan/np1/config/slave.conf

START_DELAY=.2 

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

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

source /opt/wlan/etc/meru.conf > /dev/null 2>&1
source  ${NP1SLAVE_CONF}

start() {

    # Check if np1main service is running
    if [ ! "$(/sbin/chkconfig --list | /bin/grep np1main)" ]; then
        echo "NP1 service is not set"
        return
    fi

    # Make sure we are not a master controller
    if [ -e ${NP1SLAVE_CONF} ]; then

        SELFCOUNT=`pgrep -f /etc/init.d/np1slave | wc -l`
        [$SELFCOUNT -gt 1] && {
            echo "/etc/init.d/np1slave is already running" >> $LOG
            return
        }

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

        MASTER_IP=
        # if np1s2m.sh is running loop till it stops
        i=0
        while pgrep np1s2m >/dev/null 2>&1
        do
            i=`expr $i + 1`
            echo "np1s2m.sh running; sleep 1s" >> $LOG
            sleep 1
            [ $i -gt 300 ] && {
                echo "np1s2m.sh wait timed out." >> $LOG
                return
            }
        done
                                                                      
        # if np1m2s.sh is running loop till it stops
        i=0
        while pgrep np1m2s >/dev/null 2>&1
        do
            i=`expr $i + 1`
            echo "np1m2s.sh running; sleep 1s" >> $LOG
            sleep 1
            [ $i -gt 300 ] && {
                echo "np1m2s.sh wait timed out." >> $LOG
                return
            }
        done
        
        # if meru interface exists read it IP into MASTERIP
        MASTER_IP=`ifconfig meru | perl -ne 'if (/.*inet addr:(.+?)\s/) { print $1; }'`

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

        # np1slave configuration
        export HOSTNAME
        NP1_SLAVE_IF=${REAL_IF}
        export NP1_SLAVE_IF

        $PROC $MASTER_IP > /dev/null 2>&1 < /dev/null >> $LOG 2>&1 &
        sleep $START_DELAY
        writeP1_pid
        vrfy `cat $PIDFILE 2>/dev/null` || warning "$MNAME did not start. Will try again."

    else

        echo "$MNAME service is not configured"
        return
    fi

}

stop() {

    monit_stop_process
}

case "$1" in
	start)
		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)
		start
		;;
	mstop)
		stop
		;;
	*)
		echo $"Usage: $prog {start|stop|restart}"
		exit 1
esac

exit 0
