#!/bin/sh

IFACE="wlan1"
SSID="naorobotwifi"
PSK="supermarioinreallife"

ip link set "$IFACE" up || exit 1

cat >/tmp/wpa-"$IFACE".conf <<EOF
ctrl_interface=/run/wpa_supplicant
update_config=0

network={
    ssid="$SSID"
    psk="$PSK"
    key_mgmt=WPA-PSK
}
EOF

killall wpa_supplicant 2>/dev/null

wpa_supplicant -B -i "$IFACE" -c /tmp/wpa-"$IFACE".conf || exit 1

if command -v dhclient >/dev/null 2>&1; then
    dhclient "$IFACE"
elif command -v udhcpc >/dev/null 2>&1; then
    udhcpc -i "$IFACE"
elif command -v dhcpcd >/dev/null 2>&1; then
    dhcpcd "$IFACE"
else
    echo "No DHCP client found."
    exit 1
fi

iw dev "$IFACE" link
ip addr show "$IFACE"

# Wait for DHCP to assign an address
sleep 2

IP=$(ip -4 -o addr show dev "$IFACE" | awk '{print $4}' | cut -d/ -f1)

if [ -z "$IP" ]; then
    echo "Failed to obtain an IPv4 address on $IFACE"
    exit 1
fi

# Remove any previous rules/routes
ip rule del pref 50 2>/dev/null
ip rule del from "$IP"/32 table 200 2>/dev/null
ip route flush table 200 2>/dev/null

# Policy routing for the NAO network
ip route add 192.168.0.0/24 dev "$IFACE" src "$IP" table 200
ip rule add pref 50 to 192.168.0.0/24 lookup 200
ip rule add from "$IP"/32 table 200

echo
echo "Connected on $IFACE ($IP)"
echo
ip route get 192.168.0.100
