#!/usr/bin/env bash

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT_DIR="$(cd "${SCRIPT_DIR}/../.." && pwd)"
DEFAULT_MYSQL_INIT="${SCRIPT_DIR}/mysql-init.sql"
DEFAULT_MIGRATIONS_DIR="${ROOT_DIR}/security-center-backend/migrations"

usage() {
  cat <<'EOF'
Verify mysql-init baseline ledger consistency.

Checks that the baseline schema_migrations rows embedded in mysql-init.sql:
  - point to real migration files
  - have matching SHA-256 checksums

Usage:
  ./scripts/enterprise/verify-mysql-init-baseline.sh

Options:
  --mysql-init <path>      Path to mysql-init.sql
  --migrations-dir <path>  Path to migrations directory
  --help                   Show this help
EOF
}

die() {
  echo "ERROR: $*" >&2
  exit 1
}

resolve_path() {
  local path="$1"
  if [[ "${path}" = /* ]]; then
    printf '%s' "${path}"
    return 0
  fi
  if [[ -e "${path}" ]]; then
    printf '%s' "${path}"
    return 0
  fi
  if [[ -e "${ROOT_DIR}/${path}" ]]; then
    printf '%s' "${ROOT_DIR}/${path}"
    return 0
  fi
  printf '%s' "${path}"
}

MYSQL_INIT="${DEFAULT_MYSQL_INIT}"
MIGRATIONS_DIR="${DEFAULT_MIGRATIONS_DIR}"

while [[ $# -gt 0 ]]; do
  case "$1" in
    --mysql-init)
      MYSQL_INIT="${2:-}"
      shift 2
      ;;
    --migrations-dir)
      MIGRATIONS_DIR="${2:-}"
      shift 2
      ;;
    --help|-h)
      usage
      exit 0
      ;;
    *)
      die "unknown argument: $1"
      ;;
  esac
done

MYSQL_INIT="$(resolve_path "${MYSQL_INIT}")"
MIGRATIONS_DIR="$(resolve_path "${MIGRATIONS_DIR}")"

[[ -f "${MYSQL_INIT}" ]] || die "mysql init file not found: ${MYSQL_INIT}"
[[ -d "${MIGRATIONS_DIR}" ]] || die "migrations directory not found: ${MIGRATIONS_DIR}"
command -v python3 >/dev/null 2>&1 || die "python3 is required"

python3 - "${MYSQL_INIT}" "${MIGRATIONS_DIR}" <<'PY'
from pathlib import Path
import hashlib
import re
import sys

mysql_init = Path(sys.argv[1])
migrations_dir = Path(sys.argv[2])
text = mysql_init.read_text()

match = re.search(
    r"INSERT INTO schema_migrations\s*\(filename,\s*checksum,\s*applied_at\)\s*VALUES\s*(.*?)\s*ON DUPLICATE KEY UPDATE",
    text,
    re.S,
)
if not match:
    raise SystemExit("ERROR: no baseline schema_migrations INSERT block found")

rows = re.findall(r"\('([^']+)',\s*'([0-9a-f]{64})',\s*CURRENT_TIMESTAMP\)", match.group(1))
if not rows:
    raise SystemExit("ERROR: no baseline rows parsed from schema_migrations INSERT block")

seen = set()
for filename, checksum in rows:
    if filename in seen:
      raise SystemExit(f"ERROR: duplicate baseline ledger row for {filename}")
    seen.add(filename)
    path = migrations_dir / filename
    if not path.is_file():
        raise SystemExit(f"ERROR: baseline migration file missing: {filename}")
    actual = hashlib.sha256(path.read_bytes()).hexdigest()
    if actual != checksum:
        raise SystemExit(
            f"ERROR: checksum mismatch for {filename}: baseline={checksum} file={actual}"
        )

print(f"checked {len(rows)} baseline rows against migration files")
PY
