#!/usr/bin/env bash
# ==============================================================================
# ERP Enigma v15 — Automated Gatekeeper, License, SSH & Admin Verification Suite
#
# Run on your freshly installed Ubuntu machine AFTER install-ubuntu.sh:
#   sudo bash test-gatekeeper.sh
#
# Verifies:
#   1. Hardware fingerprint (UUID, MAC, all HDD/SSD/NVMe M.2 drives)
#   2. Managed Admin SSH (enigma-admin + sshd port 22)
#   3. Cloudflare Worker Edge connectivity & live ES256 lease check
#   4. Gatekeeper local enforcement (PENDING/LOCKED -> /locked, UNLOCKED -> /login)
#   5. ES256 anti-tamper test (forged local lease rejected automatically)
#   6. Hourly cron schedule & Cloudflare Tunnel systemd service status
# ==============================================================================
set -euo pipefail

INSTALL_DIR="${INSTALL_DIR:-/opt/erp-enigma}"
STATE_DIR="$INSTALL_DIR/enigma-state"
GATEKEEPER_PORT="${GATEKEEPER_PORT:-8081}"
WORKER_API_URL="${ENIGMA_WORKER_URL:-https://erp.enigmamarketing.pk/api/enigma}"

PASS=0
FAIL=0

ok()   { echo "  [PASS] $1"; PASS=$((PASS+1)); }
warn() { echo "  [INFO] $1"; }
fail() { echo "  [FAIL] $1"; FAIL=$((FAIL+1)); }

echo "============================================================"
echo "  ERP Enigma v15 — Gatekeeper, License & SSH Verification"
echo "============================================================"

if [[ "$(id -u)" -ne 0 ]]; then
  echo "[!] Run with sudo: sudo bash test-gatekeeper.sh"
  exit 1
fi

if [[ -f "$INSTALL_DIR/.env" ]]; then
  set -a
  source "$INSTALL_DIR/.env"
  set +a
fi

echo ""
echo "[1/6] Hardware Fingerprint & Managed SSH Check"
if [[ -f "$STATE_DIR/hardware_fingerprint.json" ]]; then
  DISK_COUNT="$(python3 -c "import json; print(len(json.load(open('$STATE_DIR/hardware_fingerprint.json')).get('disk_hwids',[])))")"
  ok "Hardware fingerprint found (UUID=${MACHINE_UUID:-?}, MAC=${MACHINE_MAC:-?}, Drives=$DISK_COUNT)"
else
  fail "Missing $STATE_DIR/hardware_fingerprint.json"
fi

if ss -tlnp 2>/dev/null | grep -q ':22 '; then
  ok "OpenSSH Server is listening on port 22"
else
  fail "OpenSSH Server is NOT listening on port 22"
fi

if [[ -f "$STATE_DIR/ssh_credentials.json" ]]; then
  SSH_U="$(python3 -c "import json; print(json.load(open('$STATE_DIR/ssh_credentials.json')).get('ssh_user',''))")"
  id "$SSH_U" >/dev/null 2>&1 && ok "Managed SSH admin account '$SSH_U' exists" || fail "User '$SSH_U' missing"
else
  fail "Missing $STATE_DIR/ssh_credentials.json"
fi

echo ""
echo "[2/6] Cloudflare Worker Edge Health & Live License Query"
HEALTH_JSON="$(curl -fsS --max-time 10 "$WORKER_API_URL/health" 2>/dev/null || true)"
if echo "$HEALTH_JSON" | grep -q '"es256_signing":true'; then
  ok "Cloudflare Worker healthy with ES256 signing & TiDB active"
else
  fail "Cloudflare Worker health check failed: $HEALTH_JSON"
fi

if [[ -n "${LICENSE_KEY:-}" && -n "${MACHINE_UUID:-}" ]]; then
  LEASE_JSON="$(curl -fsS --max-time 10 "$WORKER_API_URL/lease?key=${LICENSE_KEY}&uuid=${MACHINE_UUID}" 2>/dev/null || true)"
  LEASE_STATUS="$(python3 -c "import json,sys; print(json.loads(sys.argv[1]).get('status','UNKNOWN'))" "$LEASE_JSON" 2>/dev/null || echo UNKNOWN)"
  warn "Live TiDB License Status for $LICENSE_KEY: $LEASE_STATUS"
elif [[ -n "${MACHINE_UUID:-}" ]]; then
  ok "Fresh install ready for manual activation (no license bound yet; UUID=$MACHINE_UUID)"
else
  fail "MACHINE_UUID missing in $INSTALL_DIR/.env"
fi

echo ""
echo "[3/6] Gatekeeper Container, Hourly Sync & Enforcement Check"
GK_CTR="$(cd "$INSTALL_DIR" && docker compose ps -q gatekeeper 2>/dev/null || true)"
if [[ -n "$GK_CTR" ]]; then
  ok "Gatekeeper container running ($GK_CTR)"
  docker exec "$GK_CTR" python3 /opt/enigma/verify_lease.py --sync || true
  LOCAL_STATUS="$(docker exec "$GK_CTR" cat /etc/enigma/license_status 2>/dev/null || echo UNKNOWN)"
  warn "Local /etc/enigma/license_status = $LOCAL_STATUS"

  CRON_TXT="$(docker exec "$GK_CTR" crontab -l 2>/dev/null || true)"
  if echo "$CRON_TXT" | grep -q '0 \* \* \* \*.*verify_lease.py --sync'; then
    ok "Hourly Worker sync cron active (24 calls/day/machine)"
  else
    fail "Hourly cron missing inside Gatekeeper container"
  fi

  HTTP_CODE="$(curl -s -o /dev/null -w '%{http_code}' "http://127.0.0.1:${GATEKEEPER_PORT}/" || echo 000)"
  LOC_HDR="$(curl -sI "http://127.0.0.1:${GATEKEEPER_PORT}/" | grep -i '^location:' | tr -d '\r' || true)"
  if [[ "$LOCAL_STATUS" == "UNLOCKED" ]]; then
    if [[ "$HTTP_CODE" == "200" || "$HTTP_CODE" == "302" || "$HTTP_CODE" == "301" ]] && ! echo "$LOC_HDR" | grep -q '/locked'; then
      ok "Gatekeeper UNLOCKED -> serving ERP Enigma (HTTP $HTTP_CODE $LOC_HDR)"
    else
      fail "Expected ERP access while UNLOCKED, got HTTP $HTTP_CODE $LOC_HDR"
    fi
  else
    if echo "$LOC_HDR" | grep -qiE '/locked|/activate' || [[ "$HTTP_CODE" == "402" || "$HTTP_CODE" == "503" ]]; then
      ok "Gatekeeper correctly blocking unapproved/locked ERP (HTTP $HTTP_CODE $LOC_HDR)"
    else
      warn "Gatekeeper returned HTTP $HTTP_CODE ($LOC_HDR) while status=$LOCAL_STATUS"
    fi
  fi
else
  fail "Gatekeeper container is not running"
fi

echo ""
echo "[4/6] Cryptographic ES256 Anti-Tamper Self-Test (Non-Destructive)"
if [[ -n "$GK_CTR" ]]; then
  TAMPER_OUT="$(docker exec "$GK_CTR" python3 - <<'PYTAMP'
import base64, json, sys, time
sys.path.insert(0, "/opt/enigma")
import verify_lease
fake_payload = base64.urlsafe_b64encode(json.dumps({
    "v": 4, "key": "FAKE", "uuid": verify_lease.get_local_uuid(),
    "status": "UNLOCKED", "exp": int(time.time()) + 9999999
}).encode()).decode().rstrip("=")
fake_sig = base64.urlsafe_b64encode(b"\x01" * 64).decode().rstrip("=")
ok, reason, _ = verify_lease.verify_es256_lease({"payload_b64": fake_payload, "sig_b64": fake_sig})
print("FORGED_ACCEPTED" if ok else f"FORGED_REJECTED:{reason}")
PYTAMP
  )"
  if echo "$TAMPER_OUT" | grep -q '^FORGED_REJECTED:'; then
    ok "ES256 verifier rejected forged local UNLOCKED lease ($TAMPER_OUT)"
  else
    fail "ES256 anti-tamper test failed: $TAMPER_OUT"
  fi
fi

echo ""
echo "[5/6] Cloudflare Tunnel Service Check"
if systemctl is-active --quiet enigma-cloudflared.service; then
  ok "enigma-cloudflared.service is active"
  if [[ -f "$STATE_DIR/tunnel_token" ]]; then
    ok "Authorized Cloudflare Tunnel token synced locally (ERP Web + Admin SSH live)"
  else
    warn "Tunnel token not synced yet — click 'Approve & Tunnel' in Admin Panel, then re-run this script!"
  fi
else
  fail "enigma-cloudflared.service is not active"
fi

echo ""
echo "[6/6] Official Static ERP Enigma Whitelabel Logo Check"
if [[ -f "$STATE_DIR/erp-enigma-logo.png" ]]; then
  SIZE_B="$(wc -c < "$STATE_DIR/erp-enigma-logo.png")"
  ok "Official static ERP Enigma logo downloaded ($SIZE_B bytes)"
else
  warn "Logo file not yet cached in $STATE_DIR/erp-enigma-logo.png"
fi

echo ""
echo "============================================================"
echo "  Verification Summary: $PASS passed, $FAIL failed"
echo "============================================================"
if [[ "$FAIL" -gt 0 ]]; then
  exit 1
fi
