#!/bin/sh

SSID="$1"
if [ -z "$SSID" ]; then
  IFS= read -r -p "Enter your SSID (Spaces are allowed!): " SSID
fi
[ -z "$SSID" ] && exit 1

PASS="$2"
if [ -z "$PASS" ]; then
  IFS= read -r -p "Enter your Wi-Fi password: " PASS
fi
if [ "${#PASS}" -lt "8" ] || [ "${#PASS}" -gt "63" ]; then
  echo "Passphrase must be 8..63 characters"
  exit 1
fi

wificonf_h(){
  echo 'ctrl_interface=/run/wpa_supplicant'
  echo 'update_config=1'
  echo
}

wificonf_d(){
  wificonf_h
  echo 'network={'
  echo '}'
}

wificonf(){
  wificonf_h
  wpa_passphrase ${1+"$@"} | grep -Fv '#' | sed 's/network={/network={\n\tscan_ssid=1/'
}

conf="/etc/wpa_supplicant/wpa_supplicant.conf"
wificonf "$SSID" "$PASS" > "$conf" && ret=true || ret=false
$ret || wificonf_d > "$conf"
scan_ssid=1

$ret && echo "Network Configuration Entered! To complete the setup process power your system off, making sure that only your wifi adapter is connected (Use a Y-Cable) when you turn it back on for the first time. When your console boots, you may reconnect your OTG HUB and USB drive (if applicable). Failure to do so will mean you will have to un-install the mod and restart the process." | xargs | fold -s || echo "Oops! - Something went wrong."
$ret
