#!/bin/bash

INITNAME="INIT"
DOWNNAME="DOWN"
SCANNAME="SCAN"
RUNNAME="RUN"
AUTHNAME="AUTH"
ASSOCNAME="ASSOC"

DHCLIENT_PIDFILE="/var/run/dhclient.wifi1.pid"
DHCLIENT_LEASEFILE="/var/lib/dhcp/dhclient.wifi1.leases"

currentState=`/usr/sbin/redpine/onebox_util rpine0 check_sta_state`

sleeptime=30
scanCounter=0
MAX_SCANS=6

while [ "$currentState" != "$DOWNNAME" ]
do
    echo "currentstate $currentState"
    sleeptime=10 #in transition, go fast

    #shutdown the dhclient if needed
    if [ "$currentState" != "$RUNNAME" -a "$currentState" != "$AUTHNAME" -a "$currentState" != "$ASSOCNAME" -a -f "$DHCLIENT_PIDFILE" ]; then
        echo "not running, so close down the dhclient"
        kill -15 $(cat "$DHCLIENT_PIDFILE") && rm -f "$DHCLIENT_PIDFILE"
    fi

    if [ "$currentState" = "$INITNAME" ]; then
        #if init is there, initiate a new scan
        echo "start host scan"
        scanCounter=0
        /usr/sbin/redpine/onebox_util rpine0 host_scan_2g 5 30
    elif [ "$currentState" = "$SCANNAME" ]; then
        if [ $scanCounter -gt $MAX_SCANS ]; then
            #stop scan for 60 seconds if we already scanned x times
            echo "stop scanning for a minute"
            /usr/sbin/redpine/onebox_util rpine0 host_scan_stop
            if [ "$currentState" = "$RUNNAME" ]; then
                sleeptime=1 #don't sleep, we are in run mode as we wanted, we were scanning unneeded
            else
                sleeptime=60
            fi
        fi
        #we do this a limited amount of scans to avoid lock, raise our counter
        ((scanCounter++))
        echo "raising counter to $scanCounter"
    elif [ "$currentState" = "$RUNNAME" ]; then
        if [ ! -f "$DHCLIENT_PIDFILE" ]; then
            #startup the dhclient
            echo "starting dhclient"
            /sbin/dhclient -nw -v -pf $DHCLIENT_PIDFILE -lf $DHCLIENT_LEASEFILE wifi1 -e IF_METRIC=60
        fi
        #we are connected, no need to check this to many times
        sleeptime=60
    fi

    echo "going to sleep for $sleeptime" seconds
    sleep $sleeptime
    currentState=`/usr/sbin/redpine/onebox_util rpine0 check_sta_state`
done
echo "going down"