#!/bin/bash
#RaspberryConnect.com
#Wifi config - if no prefered Wifi generate a hotspot

#This two lines check for any SSIDs in your RPi's wifi settings
#wpassid=$(awk '/ssid="/{ print $0 }' /etc/wpa_supplicant/wpa_supplicant.conf | awk -F'ssid=' '{ print $2 }' ORS=' ' | sed 's/\"/''/g')
#ssids=($wpassid)

#or check a restricted list of SSID,s that are setup. 
#Put a # infront of the two lines above first; #ssids=$(awk..... & ssids=($wpassid)
#Enter one or more ssids that are already setup in the wifi settings
#Remove # below to use. separate SSIDs by a space, ('mySSID1' 'mySSID2')
#ssids=('myssid1')
ssids=('0815' 'SUN')
#ssids=('0815off' 'SUNoff')

#Main script
createAdHocNetwork()
{
    ip link set dev wlan0 down
    ip a add 10.0.0.5/24 dev wlan0
    ip link set dev wlan0 up
    systemctl start dnsmasq
    systemctl start hostapd
}
connected=false
for ssid in "${ssids[@]}"
do
    if iw dev wlan0 scan ap-force | grep "$ssid" > /dev/null
    then
        wpa_supplicant -B -i wlan0 -c /etc/wpa_supplicant/wpa_supplicant.conf > /dev/null 2>&1
        if dhclient -1 wlan0
        then
            connected=true
            break
        else
            wpa_cli terminate
            break
        fi
    else
        echo "Not in range, WiFi with SSID:" $ssid
    fi
done
    if ! $connected; then
    createAdHocNetwork
fi
