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

START_DELAY=.2

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

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

set_myparams()
{
	set_params
	if [ -f $HOSTAPDCONF ]; then
		. $HOSTAPDCONF
	else
    	echo "$HOSTAPDCONF must exist to use $0"; exit 1
	fi

	[ "$UDP_IF" ] || fail "Cannot determine interface"

	MY_ADDR=`ifconfig $UDP_IF | grep addr: | sed -e 's/.*addr://' -e 's/ B.*//'`
	[ "$MY_ADDR" ] || fail "Cannot determine my ip"
	[ "$RADIUS_IP" ] || fail "Cannot determine radius ip"
	[ "$RADIUS_PORT" ] || fail "Cannot determine radius port"
	[ "$RADIUS_SECRET" ] || fail "Cannot determine radius secret"
	[ "$REKEY_PERIOD" ] || fail "Cannot determine rekey period"
	[ "$STA_POLL_PERIOD" ] || fail "Cannot determine poll period"
}

start() {

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

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

    #[ -f hostapd.conf ] || cp hostapd.conf.template hostapd.conf

    $PROC -o $MY_ADDR -a $RADIUS_IP -p $RADIUS_PORT -s $RADIUS_SECRET -b 13 \
        -r $REKEY_PERIOD -l $STA_POLL_PERIOD >> $LOG 2>&1 &

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

stop() {

	monit_stop_process
}

#
# main()
#

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

exit 0
