#!/bin/sh

echo "==================connect wifi ================"
set -e

SSID=$1
PSK=$2

if [ -z "$SSID" ]; then
    echo "Usage: $0 <SSID> [PSK]"
    exit 1
fi

echo "ssid :$SSID pwd :$PSK"

killall hostapd dnsmasq udhcpc wpa_supplicant 2>/dev/null || true
sleep 1

wifi_down      2>/dev/null || true
wifi_up        2>/dev/null || true

for i in $(seq 10); do
    [ -d /sys/class/net/wlan0 ] && break
    echo "wait wlan0 ... $i"
    sleep 0.5
done
[ -d /sys/class/net/wlan0 ] || { echo "wlan0 not found"; exit 1; }


if [ -n "$PSK" ]; then
cat > /tmp/wpa_supplicant.conf <<EOF
ctrl_interface=/var/run/wpa_supplicant
update_config=1
network={
    ssid="$SSID"
    psk="$PSK"
    key_mgmt=WPA-PSK
    scan_ssid=1
}
EOF
else
cat > /tmp/wpa_supplicant.conf <<EOF
ctrl_interface=/var/run/wpa_supplicant
update_config=1
network={
    ssid="$SSID"
    key_mgmt=NONE
}
EOF
fi




wpa_supplicant -Dnl80211,wext -iwlan0 -c /tmp/wpa_supplicant.conf -B
sleep 3


if wpa_cli -iwlan0 status | grep -q "wpa_state=COMPLETED"; then
    udhcpc -i wlan0 -n -q -t 5 -T 5
    echo "[DONE] IP ok"
else
    echo "[FAIL]"
    exit 1
fi
