#!/bin/bash

# Offer a dialog interface for simple wifi connection
# Exit with value 2 if SIGINT is sent.

data_out="/tmp/wifi-config.$$"
. /usr/sbin/dialog-helper

ssid=""
passphrase=""

trap "exit 2" SIGINT

while [ 1 ]; do
	wifi scan > $data_out
	ap=$(grep "wifi_" "$data_out" | sed "s/^\*A/\t/" | awk '{$(NF--)=""; print}' | sed "s/^\(.*\) $/\"\1\"/g")
	rm -f $data_out 2> /dev/null

	if [ -z "$ssid" ]; then
		eval dialog_helper --no-items --menu "'choose your AP'" 20 40 20 $ap
		ssid="$DIALOGRES"
	fi

	if [ -z "$passphrase" ]; then
		dialog_helper --inputbox "Network's passphrase (leave empty if none)" 10 40
		passphrase="$DIALOGRES"
	fi

	wifi connect "$ssid" "$passphrase" 2>1 | dialog --progressbox "Wifi connecting..." 40 100
	if [ $? -eq 0 ]; then
		dialog --msgbox "You are connected" 10 40
		exit 0
	else
		ssid=""
		passphrase=""
		dialog --yesno "Connection failed. Do you want to retry ?" 10 40 && continue
		exit 1
	fi
done
