#!/bin/bash
set -euo pipefail

CONFIG="/etc/aismap/network.json"
LOG="/var/log/aismap_to_wifi.log"
exec >"$LOG" 2>&1

echo "=== $(date) start to_wifi ==="

if [ ! -f "$CONFIG" ]; then
    echo "ERROR: config not found: $CONFIG"
    exit 1
fi

SSID=$(python3 -c "import json; print(json.load(open('$CONFIG'))['wifi_ssid'])")
PSK=$(python3 -c "import json; print(json.load(open('$CONFIG'))['wifi_psk'])")
WIFI_IP=$(python3 -c "import json; print(json.load(open('$CONFIG'))['wifi_ip'])")
GW=$(python3 -c "import json; print(json.load(open('$CONFIG')).get('wifi_gw',''))")
DNS=$(python3 -c "import json; print(json.load(open('$CONFIG')).get('wifi_dns','8.8.8.8'))")
IFACE=$(python3 -c "import json; print(json.load(open('$CONFIG')).get('iface','wlan0'))")

if [ -z "$SSID" ]; then
    echo "ERROR: wifi_ssid is empty"
    exit 1
fi

echo "[1] stop AP services"
killall hostapd 2>/dev/null || true
killall wpa_supplicant 2>/dev/null || true
sleep 1

echo "[2] reset iface $IFACE"
ip link set "$IFACE" down 2>/dev/null || true
sleep 1
ip link set "$IFACE" up
sleep 2

echo "[3] scan for SSID: $SSID"
iw dev "$IFACE" scan 2>/dev/null | grep -F "SSID: $SSID" || echo "WARN: SSID not found in scan, trying anyway"

echo "[4] build wpa config"
wpa_passphrase "$SSID" "$PSK" > /tmp/aismap_wifi.conf

echo "[5] connect to wifi"
wpa_supplicant -B -i "$IFACE" -c /tmp/aismap_wifi.conf
sleep 5

echo "[6] flush old IPs"
ip addr flush dev "$IFACE"

echo "[7] set static IP: $WIFI_IP"
ip addr add "$WIFI_IP" dev "$IFACE"

echo "[8] set default route"
ip route del default 2>/dev/null || true
if [ -n "$GW" ]; then
    ip route add default via "${GW}" dev "$IFACE"
fi

echo "[9] set DNS"
if [ -n "$DNS" ]; then
    echo "nameserver $DNS" > /etc/resolv.conf
fi

echo "[10] verify connectivity"
sleep 2
CURRENT_IP=$(ip -4 addr show "$IFACE" | grep -oP 'inet \K[0-9./]+' || echo "none")
echo "IP on $IFACE: $CURRENT_IP"

if [ -n "$GW" ]; then
    if ping -c 2 -W 3 "${GW}" >/dev/null 2>&1; then
        echo "Gateway $GW reachable — WiFi OK"
    else
        echo "WARN: gateway $GW unreachable"
    fi
else
    echo "No gateway configured, skipping ping check"
fi

echo "[11] wpa_supplicant status"
wpa_cli -i "$IFACE" status 2>/dev/null || true

ip addr show dev "$IFACE"
iw dev "$IFACE" link 2>/dev/null || true

echo "=== $(date) done to_wifi ==="
