#!/bin/sh

doswitch()
{
	ifconfig $interface down
	ifconfig $interface hw ether $macaddr
	ifconfig $interface 0.0.0.0 0.0.0.0

	ifup $interface

	wpa_supplicant -B -i$interface -Dnl80211 -c/etc/wpa_supplicant.conf

	udhcpc -i $interface -n
}

startWlan()
{
	ifconfig $interface down
	ifconfig $interface hw ether $macaddr
	ifconfig $interface 0.0.0.0 0.0.0.0

	ifup $interface
}

###this script needs an argument for the SSID we want to connect to
###in order to check if were connected to a different SSID
###if no ssid is provided then the wlan interface is just started with no arguments
interface=$1
macaddr=$2
CONNECTING_SSID=$3

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

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

NOT_ASSOCIATED="Not-Associated"
#look at the mac address of the wlan device and compare it to
#the  mac address of the current wireless networks access point
#if the two mac address's match it means we are in point to point
HW_ADDR=$(ifconfig | grep $interface | awk '{print $5}')
AP_ADDR=$(iwconfig | grep "Access Point" | awk '{print $6}' )
CONNECTED_ESSID=$(iwgetid -r)


echo "Connected $CONNECTED_ESSID and Connecting ESSID:$CONNECTING_SSID"
echo "$HW_ADDR and $AP_ADDR"
if [ "$HW_ADDR" == "$AP_ADDR" ]; then
	###were in AP mode so disable that first
	. /mnt/appdata/stophostapd.sh
	doswitch
elif [ "$AP_ADDR" == "$NOT_ASSOCIATED" ]; then
	###do the switch if we arent connected to anything either
	doswitch
elif [ -z "$CONNECTING_SSID" ] && [ $(iwgetid -r | wc -l) -eq 1 ]; then
	###on startup, this script is called. we might already be connected to an SSID
	###the system should automatically connect to this, or we relaunched qwc and 
	###it is just blindly calling this script just like it would on boot
	echo "Already connected to Infrastructure"
elif [ "$CONNECTED_ESSID" != "$CONNECTING_SSID" ]; then
	###stop wpa supplicant in case we are already connected to one
	start-stop-daemon -K -x wpa_supplicant
	doswitch
elif [ "$CONNECTING_SSID" == "" ]; then
	##calling this script with no ssid argument will allow it to just start the wlan interface
	echo "Starting wlan interface and not connecting to anything"
	startWlan
else 
	echo "Already connected to ESSID $CONNECTING_SSID"
fi
