#!/bin/bash
#
# Enables a hotspot if no working WiFi connection found
#

# sleep for a bit to give time for any working connections to come up
sleep 10
ConUp=false
# Are we connected already?
state=$(nmcli -t g | cut -f2 -d:)
if [ "$state" != "full" ]; then
	# No, so try to connect to all existing wireless connections
	interfaces=$(nmcli -t c)
	while IFS= read -r line
	do
		name="$(cut -f1 -d: <<< $line)"
		type="$(echo $line | cut -f3 -d:)"
		interface="$(echo $line | cut -f4 -d:)"
		if [ "$name" != "MyHotspot" ] && [ "$type" == "802-11-wireless" ]; then
			nmcli con up "$name" # won't return until up or failed
			# need to take the hotspot down as if the new wireless is on wlan1, this won't happen automatically
			nmcli con down "MyHotspot"
			sleep 5
			# connected now?
			state=$(nmcli -t g | cut -f2 -d:)
			if [ "$state" == "full" ]; then
				ConUp=true
			fi
		elif [ "$type" == "802-11-ethernet" ] && [ "$interface" == "eth0" ]; then
			ConUp=true
		fi
	done <<< "${interfaces}"
	
	# If no connections are working, enable the hotspot
	if [ "$ConUp" == false ]; then
		nmcli con up "MyHotspot"
	fi
fi
