#!/usr/bin/env bash
# Safe standalone script: run with `bash ./fix-status-branding.sh` from the Git checkout.
# Do not source this script (it is intentionally a standalone command).
set -Eeuo pipefail
umask 077
error(){ printf '[ERROR] %s\n' "$*" >&2; }
info(){ printf '[INFO] %s\n' "$*"; }
fail(){ error "$*"; return 1; }
trap 'error "Branding repair stopped on line $LINENO; your SQLite database was not erased."' ERR

if [[ $EUID -ne 0 ]]; then error 'Run as root (or sudo bash ./fix-status-branding.sh).'; exit 1; fi
ROOT=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
cd "$ROOT"
if [[ ! -f package.json || ! -f scripts/deploy.sh || ! -f src/branding.js ]]; then
  error 'Missing release files. Push the full External Status 1.0.9 project to Git, then pull it on VPS 2.'
  exit 1
fi
if [[ ! -x /usr/bin/node ]]; then error 'Node.js is not installed at /usr/bin/node.'; exit 1; fi
VERSION=$(/usr/bin/node -p "require('./package.json').version")
if [[ "$VERSION" != '1.0.9' ]]; then
  error "Your Git checkout is v$VERSION; expected v1.0.9. Upload/commit the new files to ArchForge, git pull, then retry."
  exit 1
fi
if ! grep -Fq "label:'ArchForge SSH'" src/probes.js || ! grep -Fq "label:'ArchForge HTTPS'" src/probes.js; then
  error 'Git checkout still contains older probe names. Commit/push/pull all v1.0.9 files.'
  exit 1
fi
info 'Deploying verified v1.0.9 source and backing up the existing database...'
bash "$ROOT/scripts/deploy.sh" "$ROOT"
INSTALLED=/opt/archforge-status/app
if [[ ! -f "$INSTALLED/package.json" || ! -f "$INSTALLED/src/branding.js" ]]; then
  error 'The installed application still lacks v1.0.9 files. Inspect systemd and deploy output.'
  exit 1
fi
if ! cmp -s "$ROOT/src/database.js" "$INSTALLED/src/database.js" || ! cmp -s "$ROOT/src/branding.js" "$INSTALLED/src/branding.js"; then
  error 'Installed source differs from v1.0.9 checkout. Check deploy location and permissions.'
  exit 1
fi
if ! systemctl is-active --quiet archforge-status; then
  error 'archforge-status is not active after deployment. Check journalctl -u archforge-status -n 40.'
  exit 1
fi
info 'Checking actual running application (not only the Git checkout)...'
HEALTH=$(curl --silent --show-error --max-time 6 --fail http://127.0.0.1:3000/healthz) || {
  error 'Local status server does not respond. Check journalctl -u archforge-status -n 40.'
  exit 1
}
if ! printf '%s' "$HEALTH" | /usr/bin/node -e 'let t="";process.stdin.on("data",c=>t+=c).on("end",()=>{try{const d=JSON.parse(t);if(d.version!=="1.0.9"||d.ok!==true)process.exit(1)}catch{process.exit(1)}})' ; then
  error "Running status server is NOT v1.0.9. Health response: $HEALTH"
  error 'Check systemctl cat archforge-status and inspect other services on port 3000.'
  exit 1
fi
info "Health endpoint confirms $HEALTH"
if command -v sqlite3 >/dev/null 2>&1 && [[ -f /var/lib/archforge-status/status.db ]]; then
  LABELS=$(sqlite3 -separator '|' /var/lib/archforge-status/status.db \
    "SELECT id,label FROM services WHERE id IN ('git_http','git_ssh') ORDER BY id;")
  printf '[INFO] Persisted labels:\n%s\n' "$LABELS"
  if [[ "$LABELS" == *'Git Smart HTTP'* || "$LABELS" == *'Git SSH'* ]]; then
    error 'Old labels are still in SQLite after successful v1.0.9 boot. Check for an alternate database or another running process.'
    exit 1
  fi
fi
info 'Done: new branding is active. Refresh https://status.archforge.nl with Ctrl+F5.'
