#!/bin/bash
set -euo pipefail
source "$(dirname "$0")/lib.sh"

ARCH="$(dpkg --print-architecture)"
case "$ARCH" in
    arm64) DEB_ARCH="arm64" ;;
    armhf) DEB_ARCH="armhf" ;;
    amd64) DEB_ARCH="amd64" ;;
    *) err "Unsupported architecture: $ARCH" ;;
esac

PAT_VER="1.0.0"
DEB="pat_${PAT_VER}_linux_${DEB_ARCH}.deb"
URL="https://github.com/la5nta/pat/releases/download/v${PAT_VER}/${DEB}"

if command -v pat >/dev/null 2>&1; then
    log "Pat already installed: $(pat version 2>/dev/null || true)"
else
    log "Installing Pat ${PAT_VER} (${DEB_ARCH})..."
    cd /tmp
    wget -q "$URL" -O "$DEB" || err "Failed to download $URL"
    sudo dpkg -i "$DEB" || sudo apt-get install -f -y
    rm -f "$DEB"
fi

# Seed a minimal config if none exists
PAT_CFG="${HAM_HOME}/.config/pat/config.json"
if [[ ! -f "$PAT_CFG" ]]; then
    log "Creating initial Pat config..."
    sudo -u "${HAM_USER}" mkdir -p "${HAM_HOME}/.config/pat"
    sudo -u "${HAM_USER}" pat configure <<EOF || true
EOF
    # Minimal surgical edits via python for valid JSON
    sudo -u "${HAM_USER}" python3 - <<PY
import json, os
path = os.path.expanduser("~/.config/pat/config.json")
# pat may use different path on first run
candidates = [
    path,
    os.path.expanduser("~/.wl2k/config.json"),
]
cfg_path = None
for c in candidates:
    if os.path.isfile(c):
        cfg_path = c
        break
if not cfg_path:
    os.makedirs(os.path.dirname(path), exist_ok=True)
    cfg = {}
    cfg_path = path
else:
    with open(cfg_path) as f:
        cfg = json.load(f)

cfg["mycall"] = "${CALLSIGN}"
cfg["locator"] = "${GRID}"
cfg["http_addr"] = "0.0.0.0:${PORT_PAT_HTTP:-8081}"
cfg.setdefault("ax25", {})
cfg["ax25"]["engine"] = "agwpe"
cfg.setdefault("agwpe", {})
cfg["agwpe"]["addr"] = "localhost:${PORT_DIREWOLF_AGW:-8000}"
cfg["agwpe"]["radio_port"] = 0

with open(cfg_path, "w") as f:
    json.dump(cfg, f, indent=2)
print("Wrote", cfg_path)
PY
else
    log "Pat config already exists — leaving it alone"
fi

log "Pat step complete — web UI will listen on port ${PORT_PAT_HTTP:-8081}"
