#!/bin/sh

# TODO: rid ourselves of plaintext configs which can have sensitive network keys

cfg_loc="/home/shockrah/.config/wifi-configs/"
iface="wlp1s0"
debug_kill=

# wpa_supplicant and dhclient are only exposed to root by default
if [ "`id -u`" -ne 0 ]
then
	echo 'Must be ran as root'
	exit 1
fi

__write_config_personal() {
printf "network={
	ssid=\"$2\"
	psk=\"$3\"
}\n" > "$cfg_loc/$1"
}

__write_config_enterprise() {
printf "network={
	ssid=\"$1\"
	scan_ssid=1
	key_mgmt=WPA-EAP
	identity=\"$2\"
	password=\"$3\"
	eap=PEAP
	phase1=\"peaplabel=0\"
	phase2=\"auth=MSCHAPV2\"
}" > "$cfg_loc/$4"
}


__kill_old() {
	if [ -z "$debug_kill" ]
	then
		kill "`pgrep wpa_supplicant`"
		dhclient -r
	else 
		echo 'Not killing anything'
	fi
}

__connect_config() {
	if [ -z "$debug_kill" ]
	then
		if [ ! -f "$1" ]; then echo Config not found\
			exit 0;fi
		__kill_old
		wpa_supplicant -B -i wlp1s0 -c "$1"
		dhclient wlp1s0
	else
		echo Not connecting to anything
	fi
}

remove_old_config() {
	name="`ls $cfg_loc | dmenu -i -p 'Name of config to remove'`"
	rm -f "$cfg_loc/$name"
}

reconnect_old_config() {
	name="`ls $cfg_loc | dmenu -i -p 'Choose config to connect with'`"
	if [ ! -z "$name" ] 
	then
		__connect_config "$cfg_loc/$name"
	fi
}

create_new_config() {
	name="`echo '' | dmenu -i -p 'Name of new config'`"
	type="`printf "WPA2 Personal\nWPA2 Enterprise" | dmenu -i -p 'Connection Type'`"
	mkdir -p $cfg_loc

	case $type in
		*Personal)
			ssid="`echo '' | dmenu -p 'SSID'`"
			psk="`echo '' | dmenu -p 'Passkey'`"
			__write_config_personal "$name" "$ssid" "$psk"
			;;
		*Enterprise)
			ssid="`echo '' | dmenu -p 'SSID'`"
			identity="`echo '' | dmenu -p 'Identity'`"
			psk="`echo '' | dmenu -p 'Passkey'`"
			__write_config_enterprise $ssid $identity $psk $name
			;;
	esac
}


option=`printf "Remove\nConnect\nNew\nDiconnect\n" | dmenu -i -p 'Options:'`
case $option in 
	New) create_new_config;;
	Remove) remove_old_config;;
	Connect) reconnect_old_config;;
	Disconnect) __kill_old;;
esac