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

# Install Graywolf from upstream GitHub releases (arm64 .deb for Pi OS 64-bit).
# Set SKIP_GRAYWOLF_INSTALL=yes in config.env to skip.

if [[ "${SKIP_GRAYWOLF_INSTALL:-}" == "yes" ]]; then
    warn "SKIP_GRAYWOLF_INSTALL=yes — not installing Graywolf"
    exit 0
fi

if command -v graywolf >/dev/null 2>&1 && systemctl list-unit-files graywolf.service 2>/dev/null | grep -q graywolf; then
    log "Graywolf already installed: $(command -v graywolf)"
    systemctl is-enabled graywolf 2>/dev/null || true
    exit 0
fi

log "Installing Graywolf (latest arm64 .deb from GitHub)..."

ARCH="$(dpkg --print-architecture 2>/dev/null || echo unknown)"
if [[ "$ARCH" != "arm64" ]]; then
    warn "Architecture is '$ARCH' (expected arm64). Trying arm64 package anyway may fail."
fi

TMPDIR="$(mktemp -d /tmp/graywolf-install-XXXXXX)"
cleanup() { rm -rf "$TMPDIR"; }
trap cleanup EXIT

API="https://api.github.com/repos/chrissnell/graywolf/releases/latest"
log "Querying $API ..."
JSON="$(curl -fsSL "$API")"
TAG="$(printf '%s' "$JSON" | python3 -c "import sys,json; print(json.load(sys.stdin)['tag_name'])")"
URL="$(printf '%s' "$JSON" | python3 -c "
import sys, json
r = json.load(sys.stdin)
for a in r.get('assets', []):
    n = a.get('name', '')
    if n.endswith('_arm64.deb') or n.endswith('_linux_arm64.deb'):
        print(a['browser_download_url'])
        break
")"

if [[ -z "${URL:-}" ]]; then
    err "Could not find an arm64 .deb asset in the latest Graywolf release ($TAG)"
    exit 1
fi

log "Downloading Graywolf $TAG ..."
DEB="$TMPDIR/graywolf.deb"
curl -fsSL -o "$DEB" "$URL"
log "Installing $(basename "$URL") ..."
sudo apt-get install -y "$DEB"

if ! systemctl list-unit-files graywolf.service 2>/dev/null | grep -q graywolf; then
    warn "graywolf.service still not present after package install — check package contents"
else
    log "graywolf.service is available"
    # Do not enable here if DEFAULT_MODEM is direwolf — 07-services.sh decides
fi

log "Graywolf install complete — configure audio/PTT/KISS in the web UI (port 8080)"
