#!/bin/bash
#
# Install AIS Map network scripts and systemd service.
# Run as root on the target device.
#
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
INSTALL_DIR="/opt/aismap/scripts"
CONFIG_DIR="/etc/aismap"
CONFIG_FILE="$CONFIG_DIR/network.json"
HOSTAPD_CONF="/etc/hostapd/hostapd.conf"

echo "=== AIS Map network scripts installer ==="

mkdir -p "$INSTALL_DIR"
mkdir -p "$CONFIG_DIR"

echo "[1] Copying scripts to $INSTALL_DIR ..."
cp "$SCRIPT_DIR/to_wifi.sh"       "$INSTALL_DIR/"
cp "$SCRIPT_DIR/to_ap.sh"         "$INSTALL_DIR/"
cp "$SCRIPT_DIR/network_init.sh"  "$INSTALL_DIR/"
chmod +x "$INSTALL_DIR"/*.sh

echo "[2] Creating default config (if not exists) ..."
if [ ! -f "$CONFIG_FILE" ]; then
    # Read current AP settings from hostapd.conf
    AP_SSID=""
    AP_PSK=""
    AP_IFACE="wlan0"
    if [ -f "$HOSTAPD_CONF" ]; then
        AP_SSID=$(grep -E '^ssid=' "$HOSTAPD_CONF" | head -1 | cut -d= -f2 || echo "")
        AP_PSK=$(grep -E '^wpa_passphrase=' "$HOSTAPD_CONF" | head -1 | cut -d= -f2 || echo "")
        AP_IFACE=$(grep -E '^interface=' "$HOSTAPD_CONF" | head -1 | cut -d= -f2 || echo "wlan0")
        echo "    Read from hostapd.conf: SSID=$AP_SSID, iface=$AP_IFACE"
    fi

    cat > "$CONFIG_FILE" <<EOF
{
  "mode": "ap",
  "wifi_ssid": "",
  "wifi_psk": "",
  "wifi_ip": "192.168.22.50/24",
  "wifi_gw": "192.168.22.1",
  "wifi_dns": "8.8.8.8",
  "ap_ip": "192.168.4.1/24",
  "ap_ssid": "$AP_SSID",
  "ap_psk": "$AP_PSK",
  "iface": "$AP_IFACE"
}
EOF
    echo "    Created $CONFIG_FILE"
else
    echo "    Config already exists, skipping"
fi

echo "[3] Installing systemd service ..."
cp "$SCRIPT_DIR/aismap-network.service" /etc/systemd/system/
systemctl daemon-reload
systemctl enable aismap-network.service
echo "    Service enabled: aismap-network.service"

echo "[4] Disabling conflicting services (optional) ..."
# We manage hostapd manually — prevent it from auto-starting
systemctl disable hostapd 2>/dev/null || true
echo "    hostapd auto-start disabled (we start it from to_ap.sh)"

echo ""
echo "=== Installation complete ==="
echo ""
echo "Usage:"
echo "  - Web UI: open Settings tab -> 'Сеть / Режим работы'"
echo "  - Manual switch to WiFi:  bash $INSTALL_DIR/to_wifi.sh"
echo "  - Manual switch to AP:    bash $INSTALL_DIR/to_ap.sh"
echo "  - Config file:            $CONFIG_FILE"
echo "  - Boot init logs:         /var/log/aismap_network_init.log"
echo "  - Hostapd backup:         ${HOSTAPD_CONF}.orig (created on first AP switch)"
echo ""
echo "On next reboot, network_init.sh will run automatically."
echo "If WiFi fails, it will roll back to AP mode."
