#!/usr/bin/env bash
set -euo pipefail

action=${1:-install}
status_url=http://127.0.0.1:47874/status
required_version='2026.08.22-host-spool-v4'
installer_url='https://thankmy.ai/broadcast/api/recording-spool-helper/artifacts/linux-installer'
installer_sha256='e2fb45f4d8c2e5105714d685a29445c4397d2dc72ee6ae1355265f57182118be'
helper_url='https://thankmy.ai/broadcast/api/recording-spool-helper/artifacts/helper'
helper_sha256='a5d50854cf55e74e8cd8ec07304f0966660cbe0fcbbb55f89192c3c2ffab6b1b'
linux_openpgp_state='not-configured'
linux_openpgp_fingerprint=''
linux_public_key_url=''
linux_installer_signature_url=''
linux_helper_signature_url=''

read_exact_status() {
  python3 - "$required_version" <<'PY'
import json
import sys
import urllib.request
required = sys.argv[1]
with urllib.request.urlopen("http://127.0.0.1:47874/status", timeout=3) as response:
    status = json.load(response)
if not (
    status.get("ok") is True
    and status.get("helper") == "thankmy_broadcast_recording_spool"
    and status.get("version") == required
    and status.get("contractVersion") == "thankmybroadcast_host_spool_v1"
    and str(status.get("platform", "")).lower().startswith("linux-")
):
    raise SystemExit("Recording Helper status is not the exact required release.")
print(json.dumps(status, separators=(",", ":")))
PY
}

if [[ "$action" == status ]]; then read_exact_status; exit 0; fi
if [[ "$action" != install && "$action" != repair && "$action" != uninstall ]]; then
  printf '%s
' "Usage: $0 [install|repair|status|uninstall]" >&2
  exit 2
fi
work_root="$(mktemp -d "${TMPDIR:-/tmp}/thankmy-broadcast-recording-helper.XXXXXX")"
trap 'rm -rf -- "$work_root"' EXIT
core_installer="$work_root/Install-ThankMyBroadcastRecordingHelper-Core.sh"
helper_path="$work_root/thankmy_broadcast_recording_spool.py"
curl --fail --silent --show-error "$installer_url" --output "$core_installer"
[[ "$(sha256sum "$core_installer" | awk '{print $1}')" == "$installer_sha256" ]] || {
  printf '%s
' "Recording Helper core installer SHA-256 verification failed." >&2; exit 1;
}
curl --fail --silent --show-error "$helper_url" --output "$helper_path"
[[ "$(sha256sum "$helper_path" | awk '{print $1}')" == "$helper_sha256" ]] || {
  printf '%s
' "Recording Helper payload SHA-256 verification failed." >&2; exit 1;
}
if [[ "$linux_openpgp_state" == valid ]]; then
  command -v gpg >/dev/null 2>&1 || {
    printf '%s
' "GnuPG is required to verify the Linux publisher signature." >&2; exit 1;
  }
  gpg_home="$work_root/gnupg"
  public_key="$work_root/publisher.asc"
  installer_signature="$work_root/installer.asc"
  helper_signature="$work_root/helper.asc"
  mkdir -m 700 "$gpg_home"
  curl --fail --silent --show-error "$linux_public_key_url" --output "$public_key"
  curl --fail --silent --show-error "$linux_installer_signature_url" --output "$installer_signature"
  curl --fail --silent --show-error "$linux_helper_signature_url" --output "$helper_signature"
  imported_fingerprint="$(gpg --batch --homedir "$gpg_home" --with-colons --import-options show-only --import "$public_key" 2>/dev/null | awk -F: '$1 == "fpr" {print $10; exit}')"
  [[ "$imported_fingerprint" == "$linux_openpgp_fingerprint" ]] || {
    printf '%s
' "Linux publisher key fingerprint did not match the release pin." >&2; exit 1;
  }
  gpg --batch --homedir "$gpg_home" --import "$public_key" >/dev/null 2>&1
  verify_linux_signature() {
    local signature="$1"
    local artifact="$2"
    local verification_status
    verification_status="$(gpg --batch --homedir "$gpg_home" --status-fd 1 --verify "$signature" "$artifact" 2>/dev/null)" || return 1
    awk -v expected="$linux_openpgp_fingerprint" '$1 == "[GNUPG:]" && $2 == "VALIDSIG" && $3 == expected {found=1} END {exit(found ? 0 : 1)}' <<<"$verification_status"
  }
  verify_linux_signature "$installer_signature" "$core_installer" || {
    printf '%s
' "Linux Recording Helper installer signature is invalid or from the wrong key." >&2; exit 1;
  }
  verify_linux_signature "$helper_signature" "$helper_path" || {
    printf '%s
' "Linux Recording Helper payload signature is invalid or from the wrong key." >&2; exit 1;
  }
else
  printf '%s
' "Linux publisher signing is not configured; this installer is integrity-pinned over HTTPS but not yet enterprise trust-ready." >&2
fi
chmod 700 "$core_installer" "$helper_path"
if [[ "$action" == uninstall ]]; then
  "$core_installer" --uninstall
else
  "$core_installer"
  read_exact_status >/dev/null
  printf '%s
' "ThankMyBroadcast Recording Helper is installed, running, and verified: $required_version"
fi
