#!/usr/bin/env bash
# Install packages from a downloaded/extracted architecture-specific bundle.
set -euo pipefail

usage() {
  echo "Usage: $0 [--gui] [--packages DIR] [--check]"
}
gui=0
check=0
package_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
while (($#)); do
  case "$1" in
    --gui) gui=1; shift;;
    --check) check=1; shift;;
    --packages) (($# >= 2)) || { usage >&2; exit 2; }; package_dir="$2"; shift 2;;
    --help|-h) usage; exit 0;;
    *) usage >&2; exit 2;;
  esac
done
fail() { echo "$*" >&2; exit 1; }
command -v dpkg >/dev/null || fail "This installer requires Debian/Raspberry Pi OS/Ubuntu with apt."
command -v apt-get >/dev/null || fail "apt-get is required."
arch="$(dpkg --print-architecture)"
case "$arch" in amd64|arm64|armhf) ;; *) fail "Unsupported OS architecture: $arch";; esac
if [[ "$arch" == armhf && "$(uname -m)" == armv6l ]]; then
  fail "This armhf build requires ARMv7 or newer; Raspberry Pi 1 / original Pi Zero need an ARMv6 build."
fi
[[ -d /run/systemd/system ]] || fail "The server requires a running systemd system (not a plain container/chroot)."

# apt checks exact library versions, including derivative distributions.
# File discovery uses package metadata, not untrusted filenames or uname alone.
shopt -s nullglob
server=()
desktop=()
for package in "$package_dir"/*.deb; do
  package_arch="$(dpkg-deb -f "$package" Architecture)"
  [[ "$package_arch" == "$arch" ]] || continue
  case "$(dpkg-deb -f "$package" Package)" in
    magic-packet-server) server+=("$package");;
    magic-packet-server-gui) desktop+=("$package");;
  esac
done
((${#server[@]} == 1)) || fail "Expected exactly one magic-packet-server package for $arch in $package_dir."
selected=("${server[0]}")
if ((gui)); then
  ((${#desktop[@]} == 1)) || fail "Expected exactly one GUI package for $arch in $package_dir."
  [[ "$(dpkg-deb -f "${server[0]}" Version)" == "$(dpkg-deb -f "${desktop[0]}" Version)" ]] || fail "Server and GUI package versions must match."
  selected+=("${desktop[0]}")
  echo "GUI needs an X11/Wayland desktop; it can be installed over SSH before logging into that desktop."
fi
for i in "${!selected[@]}"; do selected[$i]="$(realpath "${selected[$i]}")"; done
if [[ -f "$package_dir/SHA256SUMS" ]]; then
  (cd "$package_dir" && sha256sum --check SHA256SUMS)
fi
echo "OS architecture: $arch"
# Simulate before privilege escalation or any installation. Detect missing libraries.
apt-get --simulate --no-install-recommends install "${selected[@]}"
if ((check)); then exit 0; fi
if ((EUID == 0)); then
  apt-get --no-install-recommends install "${selected[@]}"
else
  sudo apt-get --no-install-recommends install "${selected[@]}"
fi
systemctl is-active --quiet magic-packet-server.service || fail "Package installed, but the service did not start; inspect journalctl -u magic-packet-server."
echo "Magic Packet Server is running. HTTP port: 5154."
