#!/bin/bash

# hotspot installer

getHotspotInfo() {
	# Open dialog to get WiFi credentials
	INFO=$(yad --form --width=420 --text-align=center --center --title="Enter Hotspot WiFi Credentials" \
	--separator="|" --item-separator="|" --borders=20 \
	--text="<b>Please enter the WiFi credentials to use when your Quadra is in HOTSPOT mode.\n</b> \
Do not use /, \", $, \[, \], or + characters"  \
	--field="SSID" "Quadra-Hotspot" \
	--field="PASSORD" "1n0v@t0!" \
	--field="<b>Password is case sensitive</b>.\n\nIf you use the default password, please note extra  '!' at end.":LBL \
	--button="Continue":0 \
	--button="Exit":1 "" "" "")

	BUT=$(echo $?)
	if [ ${BUT} = 1 ]; then
		exit
	fi

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

	#Check password length
	passLen=${#password}
	if [ ${passLen} -lt 8 ]; then
		yad --center --form --width=300 --height=200 --separator="|" \
			--borders=20 \
			--text="<b>Hotspot password has to be at least 8 characters</b>" --title="73 Linux" \
			--button=gtk-ok
		getHotspotInfo
	fi
}


# Create hotspot network connection
if [[ $(nmcli c) != *"MyHotspot"* ]]; then
	getHotspotInfo

	echo "ADDING HOTSPOT"
	# copy service file
	sudo mv hotspot.service /etc/systemd/system
	# copy bin
	sudo mv hotspot /usr/sbin
	# copy make-con
	sudo mv make-con /usr/bin
	# create network connection
	sudo nmcli con add type wifi ifname wlan0 con-name MyHotspot autoconnect yes ssid "$ssid"
	sudo nmcli con modify MyHotspot 802-11-wireless.mode ap 802-11-wireless.band bg ipv4.method shared
	sudo nmcli con modify MyHotspot wifi-sec.key-mgmt wpa-psk
	sudo nmcli con modify MyHotspot wifi-sec.psk "$password"
	sudo nmcli con modify MyHotspot ipv4.addresses "10.10.10.1/24"

	# install and configure dnsmasq
	sudo apt install -y dnsmasq
	cat <<EOF >> dnsmasq.conf
	dhcp-range=10.10.10.2,10.10.10.5,12h
	server=8.8.8.8
	listen-address=10.10.10.1,127.0.0.1
	interface=wlan0
EOF
	sudo mv dnsmasq.conf /etc/
	sudo systemctl enable dnsmasq
	sudo systemctl enable hotspot
fi


