#!/usr/bin/env bash
# Read-only deploy parity check for the 110 cold-start monitor.

set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
REMOTE="${REMOTE:-wooo@192.168.0.110}"
SSH_BATCH_MODE="${SSH_BATCH_MODE:-yes}"
SSH_STRICT_HOST_KEY_CHECKING="${SSH_STRICT_HOST_KEY_CHECKING:-accept-new}"
PROMETHEUS_URL="${PROMETHEUS_URL:-http://192.168.0.110:9090}"

ssh_opts=(-o BatchMode="$SSH_BATCH_MODE" -o ConnectTimeout=6 -o StrictHostKeyChecking="$SSH_STRICT_HOST_KEY_CHECKING")

local_sha256() {
  if command -v sha256sum >/dev/null 2>&1; then
    sha256sum "$1" | awk '{print $1}'
  else
    shasum -a 256 "$1" | awk '{print $1}'
  fi
}

remote_sha256() {
  ssh "${ssh_opts[@]}" "$REMOTE" "sha256sum '$1' 2>/dev/null | awk '{print \$1}'"
}

require_same_hash() {
  local local_path="$1"
  local remote_path="$2"
  local label="$3"
  local local_hash remote_hash

  local_hash="$(local_sha256 "$ROOT_DIR/$local_path")"
  remote_hash="$(remote_sha256 "$remote_path")"
  if [ -z "$remote_hash" ]; then
    echo "BLOCKED $label missing on $REMOTE: $remote_path" >&2
    return 1
  fi
  if [ "$local_hash" != "$remote_hash" ]; then
    echo "BLOCKED $label hash mismatch local=$local_hash remote=$remote_hash" >&2
    return 1
  fi
  echo "OK $label hash matches $REMOTE"
}

require_remote_pattern() {
  local pattern="$1"
  local path="$2"
  local label="$3"
  if ssh "${ssh_opts[@]}" "$REMOTE" "grep -Fq '$pattern' '$path'"; then
    echo "OK $label"
  else
    echo "BLOCKED $label missing in $path" >&2
    return 1
  fi
}

require_no_cold_start_alerts() {
  PROMETHEUS_URL="$PROMETHEUS_URL" python3 - <<'PY'
import json
import os
import sys
import urllib.parse
import urllib.request

base_url = os.environ["PROMETHEUS_URL"].rstrip("/")
expr = 'ALERTS{alertname=~"ColdStart.*",alertstate="firing"}'
url = base_url + "/api/v1/query?" + urllib.parse.urlencode({"query": expr})
payload = json.load(urllib.request.urlopen(url, timeout=8))
if payload.get("status") != "success":
    print(f"BLOCKED Prometheus query failed: {payload}", file=sys.stderr)
    sys.exit(1)
rows = payload.get("data", {}).get("result") or []
if rows:
    names = sorted({(row.get("metric") or {}).get("alertname", "unknown") for row in rows})
    print("BLOCKED ColdStart alerts still firing: " + ", ".join(names), file=sys.stderr)
    sys.exit(1)
print("OK Prometheus has no ColdStart firing alerts")
PY
}

require_same_hash \
  "scripts/reboot-recovery/full-stack-cold-start-check.sh" \
  "/home/wooo/scripts/full-stack-cold-start-check.sh" \
  "full-stack-cold-start-check.sh"

require_same_hash \
  "scripts/reboot-recovery/cold-start-textfile-exporter.sh" \
  "/home/wooo/scripts/cold-start-textfile-exporter.sh" \
  "cold-start-textfile-exporter.sh"

require_remote_pattern \
  "StrictHostKeyChecking" \
  "/home/wooo/scripts/full-stack-cold-start-check.sh" \
  "110 deployed check script carries SSH host-key policy"

require_remote_pattern \
  'awoooi_cold_start_warn_gates{host="110",scope="110_120_121_188"} 0' \
  "/home/wooo/node_exporter_textfiles/cold_start_recovery.prom" \
  "110 cold-start warn metric is green"

require_remote_pattern \
  'awoooi_cold_start_last_result{host="110",scope="110_120_121_188",result="green"} 1' \
  "/home/wooo/node_exporter_textfiles/cold_start_recovery.prom" \
  "110 cold-start result metric is green"

require_no_cold_start_alerts

echo "COLD_START_MONITOR_DEPLOY_PARITY_OK"
