#!/bin/sh

pbc()
{
	echo "Starting PBC mode"
	echo "Push button on the station within two minutes"
	if ! hostapd_cli wps_pbc | grep -q OK; then
		echo "Failed to enable PBC mode"
	fi
}

enter_pin()
{
	echo "Enter a PIN from a station to be enrolled to the network."
	read -p "Enrollee PIN: " pin
	cpin=`hostapd_cli wps_check_pin "$pin" | tail -1`
	if [ "$cpin" = "FAIL-CHECKSUM" ]; then
		echo "Checksum digit is not valid"
		read -p "Do you want to use this PIN (y/n)? " resp
		case "$resp" in
			y*)
				cpin=`echo "$pin" | sed "s/[^1234567890]//g"`
				;;
			*)
				return 1
				;;
		esac
	fi
	if [ "$cpin" = "FAIL" ]; then
		echo "Invalid PIN: $pin"
		return 1
	fi
	echo "Enabling Enrollee PIN: $cpin"
	if ! hostapd_cli wps_pin any "$cpin" | grep -q OK; then
		echo "Failed to enable Enrollee PIN"
	fi
}

show_config()
{
	echo "2.4 GHz radio:"
	hostapd_cli -iath0 get_config
	echo
	echo "5 GHz radio:"
	hostapd_cli -iath1 get_config
	echo
	echo "AP PIN `hostapd_cli wps_ap_pin get | tail -1`"
}

config_ap()
{
	echo
	echo "Change AP configuration"

	read -p "SSID: " ssid

	echo
	echo "Available authentication modes:"
	echo "1: Open (no security)"
	echo "2: WPA/WPA2-Personal mixed mode"
	echo "3: WPA2-Personal (CCMP only)"
	read -p "Authentication mode: " authmode
	case "$authmode" in
		1)
			echo "Note: Anyone could connect to the network!"
			read -p "Do you want to continue (y/n) ? " resp
			case "$resp" in
				y*)
					;;
				*)
					return 1
					;;
			esac
			auth="OPEN"
			encr="NONE"
			key=""
			;;
		2)
			auth="WPAPSK"
			encr="TKIP"
			read -p "Passphrase: " key
			;;
		3)
			auth="WPA2PSK"
			encr="CCMP"
			read -p "Passphrase: " key
			;;
		*)
			echo "Invalid mode: $authmode"
			return 1
			;;
	esac

	echo
	echo "Configuring AP:"
	echo "SSID: $ssid"
	echo "auth=$auth"
	echo "encr=$encr"
	if [ -n "$key" ]; then
		echo "key=$key"
	fi

	if ! hostapd_cli wps_config "$ssid" $auth $encr "$key" | grep -q OK; then
		echo "Failed to configure AP"
	fi
}

main_menu()
{
	echo "Atheros AP"
	echo "----------"
	echo "1: Push button (activate PBC)"
	echo "2: Enter Enrollee PIN"
	echo "3: Show AP configuration"
	echo "4: Configure AP"
	echo "5: Reset to out-of-box configuration"
	echo "0: Exit wpscli"

	read -p "Command: " cmd

	case "$cmd" in
		1)
			pbc
			;;
		2)
			enter_pin
			;;
		3)
			show_config
			;;
		4)
			config_ap
			;;
		5)
			echo "Resetting AP to out-of-box configuration"
			apoob
			;;
		0)
			exit 0
			;;
		*)
			echo "Unknown command: $cmd"
			;;
	esac

	echo
	main_menu
}


main_menu
