#!/bin/bash

getWifiInfo() {
	#unblock wifi
	#sudo rfkill unblock all >/dev/null 2>&1
	#bring wifi up
	#sudo ifconfig wlan0 up
	#LIST=$(sudo iw dev "wlan0" scan ap-force | sed -ne 's/^.*SSID: \(..*\)/\1/p' | sed 's/\\x20/ /g' | sort | uniq | paste -sd '|')
	INFO=$(yad --center --form --width=400 --height=200 --separator="|" --item-separator="|" \
		--column=Check --column=ssid --column=Description \
		--text-align=center --borders=20  \
		--text="<b>Please enter your WiFi credentials below:</b>" \
		--title="select Network" \
		--field="Wifi SSID" \
		--field="Wifi Password" \
		--button="Exit":1 \
		--button="Continue":2)
	BUT=$?

	if [ ${BUT} = 252 ] || [ ${BUT} = 1 ]; then
		exit
	fi

	ssid="$(cut -f1 -d\| <<< $INFO)"
	password=$(echo ${INFO} | awk -F "|" '{print $2}')
}

# Open dialog to get WiFi credentials

getWifiInfo

echo "SSID: $ssid PASSwORD: $password"
interface="wlan0"

# See if wlan1 exists and if so, use it
if [[ $(nmcli d) == *"wlan1"* ]]; then
	echo "Using WLAN1"
	interface="wlan1"
fi

# disable HotSpot as now have a real connection
nmcli con down "MyHotspot"

# Create connection
if [[ $(nmcli c) != *"$ssid"* ]]; then
	sudo nmcli con add type wifi ifname "$interface" con-name "$ssid" autoconnect yes ssid "$ssid"
fi
sudo nmcli con modify "$ssid" 802-11-wireless.mode infrastructure 802-11-wireless.band bg ipv4.method auto
sudo nmcli con modify "$ssid" wifi-sec.key-mgmt wpa-psk
sudo nmcli con modify "$ssid" wifi-sec.psk "$password"
nmcli con up "$ssid"

