#!/bin/sh
# wifi-set: change the Wi-Fi network without reflashing.
#   wifi-set "SSID" "PASSWORD"      save; used from next boot
#   wifi-set "SSID" ""              open network (no password)
#   wifi-set "SSID" "PASSWORD" now  save + switch immediately (SSH will drop; if the new
#                                   network doesn't connect in 40s it reverts automatically)
#   wifi-set --show | --forget      show current network / delete saved network (-> default)
# Saved to /data/wpa_supplicant.conf; previous one kept as .prev. Boot tries:
#   new -> previous -> build-time default, first that connects wins.
CONF=/data/wpa_supplicant.conf
case "$1" in
    --show)   for c in $CONF /usr/local/wpa_default.conf; do [ -f $c ] && { echo "$c:"; grep -E '^\s*(ssid|#ssid)' $c; }; done
              wpa_cli -iwlan0 status 2>/dev/null | grep -E '^(ssid|wpa_state|ip_address)='; exit 0 ;;
    --forget) rm -f $CONF $CONF.prev; echo "saved network removed (build default used next boot)"; exit 0 ;;
    ""|-h|--help) sed -n '2,10p' "$0"; exit 2 ;;
esac
SSID=$1; PSK=$2
[ ${#SSID} -ge 1 ] && [ ${#SSID} -le 32 ] || { echo "SSID must be 1-32 bytes"; exit 1; }
[ -z "$PSK" ] || { [ ${#PSK} -ge 8 ] && [ ${#PSK} -le 63 ]; } || { echo "password must be 8-63 chars (or empty for open)"; exit 1; }
/usr/sbin/wifi-mkconf "$SSID" "$PSK" > $CONF.new || exit 1
[ -f $CONF ] && cp -f $CONF $CONF.prev
mv -f $CONF.new $CONF; sync
echo "saved network \"$SSID\" to $CONF"
if [ "$3" = now ]; then
    echo "switching now; if it fails the camera reverts to the previous network within ~40s"
    setsid /usr/sbin/wifi-connect --switch </dev/null >/tmp/wifi-switch.log 2>&1 &
else
    echo "takes effect on next boot (reboot), or rerun with 'now' as 3rd arg"
fi
