#!/bin/bash
set -euo pipefail

CONFIG="/etc/aismap/network.json"
HOSTAPD_CONF="/etc/hostapd/hostapd.conf"
LOG="/var/log/aismap_to_ap.log"
exec >"$LOG" 2>&1

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

IFACE="wlan0"
AP_IP="192.168.4.1/24"
AP_SSID=""
AP_PSK=""

if [ -f "$CONFIG" ]; then
    IFACE=$(python3 -c "import json; print(json.load(open('$CONFIG')).get('iface','wlan0'))" 2>/dev/null || echo "wlan0")
    AP_IP=$(python3 -c "import json; print(json.load(open('$CONFIG')).get('ap_ip','192.168.4.1/24'))" 2>/dev/null || echo "192.168.4.1/24")
    AP_SSID=$(python3 -c "import json; print(json.load(open('$CONFIG')).get('ap_ssid',''))" 2>/dev/null || echo "")
    AP_PSK=$(python3 -c "import json; print(json.load(open('$CONFIG')).get('ap_psk',''))" 2>/dev/null || echo "")
fi

echo "[1] stop wifi client"
killall wpa_supplicant 2>/dev/null || true
sleep 1

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

echo "[3] restore AP IP: $AP_IP"
ip addr add "$AP_IP" dev "$IFACE"

echo "[4] update hostapd.conf (if new SSID/PSK provided)"
if [ -n "$AP_SSID" ] && [ -f "$HOSTAPD_CONF" ]; then
    # Back up the original before first modification
    if [ ! -f "${HOSTAPD_CONF}.orig" ]; then
        cp "$HOSTAPD_CONF" "${HOSTAPD_CONF}.orig"
        echo "    backed up original to ${HOSTAPD_CONF}.orig"
    fi
    sed -i "s/^ssid=.*/ssid=${AP_SSID}/" "$HOSTAPD_CONF"
    echo "    ssid -> $AP_SSID"
    if [ -n "$AP_PSK" ]; then
        sed -i "s/^wpa_passphrase=.*/wpa_passphrase=${AP_PSK}/" "$HOSTAPD_CONF"
        echo "    wpa_passphrase -> (updated)"
    fi
    # Keep interface in sync
    sed -i "s/^interface=.*/interface=${IFACE}/" "$HOSTAPD_CONF"
else
    echo "    no SSID in config or hostapd.conf missing — using existing hostapd.conf"
fi

echo "[5] start hostapd"
hostapd -B "$HOSTAPD_CONF"

echo "[6] restart dnsmasq (if used)"
systemctl restart dnsmasq 2>/dev/null || true

echo "[7] status"
ip addr show dev "$IFACE"
iw dev 2>/dev/null || true

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