#!/bin/sh
#
# Copyright 2003 Meru Networks
# All rights reserved.
#
PROC=/usr/sbin/httpd
START_DELAY=.2

MNAME=`basename $PROC`
PIDFILE=/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

start() {

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

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

	/usr/sbin/apachectl start >> $LOG 2>&1 &
	sleep $START_DELAY
	check_pid
	vrfy `cat $PIDFILE 2>/dev/null` || warning "$PROC did not start. Will try again."
}

stop() {
	/usr/sbin/apachectl stop >> $LOG 2>&1 &

	# wait until semapthores are completely cleaned up
	i=0
	max=10

	while [ $i -le $max ];
	do
		CNT=`ipcs -s | grep nobody | awk '{ print $2 }'`
		if [ "$CNT" = "" ]; then
			break
		fi
		echo "remaining semId $CNT" >> $LOG 2>&1
		sleep 1

		# increase count
		i=`expr $i + 1`
	done

	# if semId still exists, clean it up in force
	if [ "$CNT" != "" ]; then
		echo "remaining semId $CNT terminating ..." >> $LOG 2>&1
		ipcs -s | grep nobody | awk '{ print $2 }' | xargs ipcrm sem >> $LOG 2>&1
	fi

	# clean up ssl mutex files
	rm -f /opt/wlan/var/log/ssl_mutex.* >> $LOG 2>&1

	monit_stop_process
}

case "$1" in
	start)
		if vrfy monit; then
			start_with_monit apache
		else
			start
		fi
		;;
	stop)
		if vrfy monit; then
                        stop_with_monit apache
		else
			stop
		fi
		;;
	restart)
		# check if nplus1 runs with passive slave role
		check_np1_role

		if vrfy monit; then
                        restart_with_monit apache
		else
			stop
			start
		fi
		;;
	mstart)
		start
		;;
	mstop)
		stop
		;;
	*)
		echo $"Usage: $prog {start|stop|restart}"
		exit 1
esac

exit 0
