#!/bin/sh

interface=$1
hotspot_macaddr=$2

if [ -z $interface ]
then
	echo "Please pass valid wlan interface"
	exit 1
fi

if [ -z $hotspot_macaddr ]
then
	echo "Please pass valid wlan interface mac address"
	exit 1
fi

HOTSPOT_IP="192.168.2.1"
HOSTAPD="hostapd"
IP_ADDR=$(ifconfig | grep $interface -A 1 | grep -Ev 'wlan1' | awk -F: '{print $2}' | awk '{print $1}')
GREP_HOSTAPD=$(ps | grep hostapd | awk 'NR==1{print $5}')

starthostapd()
{
        ifconfig $interface down
        sleep 0.25
        ifconfig $interface hw ether $hotspot_macaddr
        ifconfig $interface 192.168.2.1
        ifconfig $interface up

        count=1
        while [ $count -le 5 ]
        do
            cmdstatus=`ip link show $interface | grep -iq up ; echo $?`

            if [ 1 = $cmdstatus ]
            then
                echo "wlan interface is not up - $count"
                # forever sleep - without wlan interface the tool is of no use
                sleep 1
            else
                echo "wlan interface up and running!!"
                break
            fi
       done

        # clear any cached hostapd configurations
        rm -rf /var/run/hostapd

        start-stop-daemon -S -x hostapd -- /etc/hostapd.conf -B
        start-stop-daemon -S -x dnsmasq -- -7 /etc/dnsmasq.d
}

if [ "$IP_ADDR" == "$HOTSPOT_IP" ]; then
        if [ "$GREP_HOSTAPD" == "$HOSTAPD" ]; then
                echo "Access point is already enabled. Disable the hostpot first"
        else 
                starthostapd
        fi
else 
        starthostapd
fi

