#!/bin/bash
#
# AIS Map network init — runs at boot.
# Reads /etc/aismap/network.json, tries the configured mode.
# If mode=wifi and connection fails — rolls back to AP.
#

set -uo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
CONFIG="/etc/aismap/network.json"
LOG="/var/log/aismap_network_init.log"
exec >"$LOG" 2>&1

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

if [ ! -f "$CONFIG" ]; then
    echo "Config not found ($CONFIG), defaulting to AP mode"
    bash "$SCRIPT_DIR/to_ap.sh"
    echo "=== $(date) network_init done (default AP) ==="
    exit 0
fi

MODE=$(python3 -c "import json; print(json.load(open('$CONFIG')).get('mode','ap'))" 2>/dev/null || echo "ap")
echo "Configured mode: $MODE"

if [ "$MODE" = "wifi" ]; then
    echo "--- Attempting WiFi connection ---"
    bash "$SCRIPT_DIR/to_wifi.sh"
    WIFI_EXIT=$?

    if [ $WIFI_EXIT -ne 0 ]; then
        echo "to_wifi.sh failed (exit $WIFI_EXIT) — rolling back to AP"
        bash "$SCRIPT_DIR/to_ap.sh"
        echo "=== $(date) network_init done (rollback to AP) ==="
        exit 0
    fi

    GW=$(python3 -c "import json; print(json.load(open('$CONFIG')).get('wifi_gw',''))" 2>/dev/null || echo "")
    IFACE=$(python3 -c "import json; print(json.load(open('$CONFIG')).get('iface','wlan0'))" 2>/dev/null || echo "wlan0")

    echo "Verifying WiFi connectivity (gateway: $GW) ..."
    CONNECTED=0
    for ATTEMPT in 1 2 3; do
        sleep 3
        if [ -n "$GW" ] && ping -c 2 -W 3 "$GW" >/dev/null 2>&1; then
            echo "Attempt $ATTEMPT: gateway reachable"
            CONNECTED=1
            break
        fi
        # Also check wpa_supplicant state
        if wpa_cli -i "$IFACE" status 2>/dev/null | grep -q "wpa_state=COMPLETED"; then
            echo "Attempt $ATTEMPT: wpa_supplicant COMPLETED"
            CONNECTED=1
            break
        fi
        echo "Attempt $ATTEMPT: not connected yet..."
    done

    if [ $CONNECTED -eq 1 ]; then
        echo "WiFi connection confirmed"
        echo "=== $(date) network_init done (wifi) ==="
        exit 0
    else
        echo "WiFi NOT reachable after 3 attempts — rolling back to AP"
        bash "$SCRIPT_DIR/to_ap.sh"
        echo "=== $(date) network_init done (rollback to AP) ==="
        exit 0
    fi
else
    echo "--- Starting AP mode ---"
    bash "$SCRIPT_DIR/to_ap.sh"
    echo "=== $(date) network_init done (ap) ==="
    exit 0
fi
