#!/usr/bin/env bash
# Pre-flight checks for remote-access v1 on the BE (run on Alpine VM as root or deploy user).
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT"

# Alpine BE: default `php` may be 8.5 without session; php-fpm81 uses 8.1.
php_bin() {
  if [[ -n "${PHP_BIN:-}" ]]; then
    echo "$PHP_BIN"
    return
  fi
  if php -m 2>/dev/null | grep -qi '^session$'; then
    echo php
    return
  fi
  if command -v php81 >/dev/null 2>&1 && php81 -m 2>/dev/null | grep -qi '^session$'; then
    echo php81
    return
  fi
  echo php
}
PHP="$(php_bin)"

fail=0
warn=0

ok() { echo "OK   $*"; }
bad() { echo "FAIL $*"; fail=1; }
note() { echo "WARN $*"; warn=1; }

echo "== Remote access production verify =="
echo "backend: $ROOT"
echo

# config.php
CFG="$ROOT/config/config.php"
if [[ ! -f "$CFG" ]]; then
  bad "config/config.php missing (copy from config.example.php)"
else
  ok "config.php present"
fi

"$PHP" -r '
$config = require "'"$CFG"'";
$ra = $config["remote_access"] ?? [];
$pub = trim((string)($ra["wg_server_public_key"] ?? ""));
$ep = trim((string)($ra["wg_endpoint"] ?? ""));
if ($pub === "") { fwrite(STDERR, "FAIL wg_server_public_key is empty — run: wg show wg0 public-key\n"); exit(2); }
if ($ep === "") { fwrite(STDERR, "FAIL wg_endpoint is empty\n"); exit(2); }
if (empty($ra["require_wg_tools"])) { fwrite(STDERR, "WARN require_wg_tools should be true on production\n"); exit(3); }
echo "OK   remote_access config: endpoint=$ep, require_wg_tools=" . (($ra["require_wg_tools"] ?? false) ? "true" : "false") . "\n";
' || {
  code=$?
  if [[ $code -eq 2 ]]; then fail=1; elif [[ $code -eq 3 ]]; then warn=1; fi
}

# wireguard-tools
if command -v wg >/dev/null 2>&1; then
  ok "wg in PATH ($(command -v wg))"
else
  bad "wireguard-tools missing (apk add wireguard-tools)"
fi

IFACE="${WG_INTERFACE:-wg0}"
if ip link show "$IFACE" >/dev/null 2>&1; then
  ok "interface $IFACE up"
  if command -v wg >/dev/null 2>&1; then
    wg show "$IFACE" 2>/dev/null | head -3 || note "wg show $IFACE returned nothing"
  fi
else
  note "interface $IFACE not found (data plane not ready; HTTP control plane may still work)"
fi

# PHP can shell_exec wg (same user as FPM)
if "$PHP" -r 'echo trim((string)@shell_exec("wg genkey 2>/dev/null"));' | grep -qE '.{40,}'; then
  ok "php can run wg genkey (FPM user must match for connect)"
else
  note "php CLI cannot run wg genkey — ensure www-data can run wg if provision_peers=true"
fi

# DB tables (via bootstrap)
"$PHP" -r '
require "'"$ROOT"'/src/bootstrap.php";
RemoteAccessRepository::ensureSchema();
$pdo = Database::pdo();
foreach (["remote_access_devices","remote_access_sessions","remote_access_events"] as $t) {
  if (!Database::tableExists($pdo, $t)) { fwrite(STDERR, "FAIL table missing: $t\n"); exit(2); }
}
echo "OK   MariaDB/SQLite remote_access tables present\n";
' || fail=1

# API smoke (local php -S or deployed BASE)
BASE="${BASE:-${CRASHES_BASE:-http://127.0.0.1:8080/app/androidcast_project/crashes}}"
if [[ -x "$ROOT/scripts/test_remote_access_api.sh" ]]; then
  if CRASHES_BASE="$BASE" bash "$ROOT/scripts/test_remote_access_api.sh" >/dev/null 2>&1; then
    ok "API smoke test ($BASE)"
  else
    note "API smoke test failed against $BASE (set BASE or CRASHES_BASE=…/crashes)"
  fi
fi

if [[ "${RA_E2E:-}" == "1" ]] && [[ -x "$ROOT/scripts/ra_e2e_cli.sh" ]]; then
  if command -v jq >/dev/null 2>&1; then
    if CRASHES_BASE="$BASE" bash "$ROOT/scripts/ra_e2e_cli.sh" >/dev/null 2>&1; then
      ok "RA E2E CLI ($BASE)"
    else
      note "RA E2E CLI failed against $BASE (needs jq, admin login, remote_access RBAC)"
    fi
  else
    note "RA E2E skipped (install jq)"
  fi
fi

echo
if [[ $fail -ne 0 ]]; then
  echo "Result: NOT READY ($fail hard failure(s), $warn warning(s))"
  exit 1
fi
if [[ $warn -ne 0 ]]; then
  echo "Result: READY WITH WARNINGS ($warn warning(s))"
  exit 0
fi
echo "Result: READY"
exit 0
