#!/bin/bash
# Set passphrase for PiWifiAP wireless access point

current_user=`whoami`
if [ "$current_user" != "root" ]
then
	echo "You must have root privileges to run this setup."
	echo "Try 'sudo $0'"
	exit 1
fi

source /etc/piwifiap/piwifiap.conf

wappassok="no"
while [[ "$wappassok" == "no" ]]
do
	echo "You will need to set a passphrase for this access point. It should"
	echo "be at least 8 characters in length and cannot be blank."
	echo -n "Please enter the desired passphrase for this access point:  "
	read wappass
	wappasslen=$(echo -n $wappass | wc -m)
	if [[ "$wappass" == "" || $wappasslen -lt 8 ]]
	then
		echo "Passphrase doesn't satisfy requirements above. Try again."
	else
		wappassok="yes"
	fi
done

case "$network_system" in
	"systemd-networkd")
		sed -i "/wpa_passphrase=.*/c wpa_passphrase=$wappass" /etc/hostapd/hostapd.conf
    	systemctl restart hostapd
		sed -i 's|'wappass=.*'|'wappass="\'$wappass\'"'|' /etc/piwifiap/piwifiap.conf
		sed -i 's|'802-11-wireless-security.psk:.*'|'802-11-wireless-security.psk:$wappass'|' /etc/piwifiap/piwifiap.secret
		;;
	"NetworkManager")
		nmcli con down piwifi-hotspot
		sed -i 's|'wappass=.*'|'wappass="\'$wappass\'"'|' /etc/piwifiap/piwifiap.conf
		sed -i 's|'802-11-wireless-security.psk:.*'|'802-11-wireless-security.psk:$wappass'|' /etc/piwifiap/piwifiap.secret
		nmcli con up piwifi-hotspot passwd-file /etc/piwifiap/piwifiap.secret
		;;
	*)
		echo "Unable to determine what type of network configuration (systemd-networkd"
		echo "or NetworkManager) your system uses."
		echo "Cannot modify wireless access point parameters."
		exit 2
		;;
esac
