#!/bin/sh
# wifi-connect [--switch]: bring wlan0 up on the first config that associates.
# Order: /data/wpa_supplicant.conf, its .prev, /etc/config/wpa_supplicant.conf,
# /usr/local/wpa_default.conf (build-time). If none connects, stay on the first one
# (wpa_supplicant keeps retrying, e.g. router still booting after a power cut).
PATH=$PATH:/bin:/sbin:/usr/bin:/usr/sbin
try() {
    killall udhcpc wpa_supplicant 2>/dev/null; sleep 1
    wpa_supplicant -B -iwlan0 -Dnl80211 -c "$1" || return 1
    i=0; while [ $i -lt ${2:-30} ]; do
        [ "$(wpa_cli -iwlan0 status 2>/dev/null | sed -n 's/^wpa_state=//p')" = COMPLETED ] && return 0
        sleep 1; i=$((i+1)); done
    return 1
}
LIST=
for c in /data/wpa_supplicant.conf /data/wpa_supplicant.conf.prev /etc/config/wpa_supplicant.conf /usr/local/wpa_default.conf; do
    [ -f "$c" ] && LIST="$LIST $c"
done
[ -n "$LIST" ] || { echo "[wifi] no network configured (put wifi.txt on the SD card)"; exit 1; }
FIRST=; OK=
for c in $LIST; do
    [ -f "$c" ] || continue                 # .prev may have been consumed by a revert
    [ -n "$FIRST" ] || FIRST=$c
    echo "[wifi] trying $c"
    if try "$c" 40; then OK=$c; break; fi
    echo "[wifi] $c did not connect"
    # wifi-set ... now: a new network that fails is reverted immediately and retried
    if [ "$1" = --switch ] && [ "$c" = /data/wpa_supplicant.conf ] && [ -f /data/wpa_supplicant.conf.prev ]; then
        mv -f /data/wpa_supplicant.conf /data/wpa_supplicant.conf.failed
        mv -f /data/wpa_supplicant.conf.prev /data/wpa_supplicant.conf; sync
        echo "[wifi] reverted to previous network (bad one kept as .failed)"
        FIRST=/data/wpa_supplicant.conf
        if try /data/wpa_supplicant.conf 40; then OK=/data/wpa_supplicant.conf; break; fi
    fi
done
if [ -z "$OK" ]; then
    echo "[wifi] nothing connected; staying on $FIRST and retrying in background"
    killall wpa_supplicant 2>/dev/null; sleep 1
    wpa_supplicant -B -iwlan0 -Dnl80211 -c "$FIRST"
else
    echo "[wifi] connected using $OK"
fi
udhcpc -i wlan0 -b
ifconfig wlan0
