#!/bin/bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
DB_URL="${GNEXUS_BOOK_DATABASE_URL:-}"
if [ -z "$DB_URL" ]; then
  echo "GNEXUS_BOOK_DATABASE_URL is required" >&2
  exit 2
fi

DEST="${GNEXUS_BOOK_BACKUP_DIR:-$HOME/NetTera8/service/backups/gnexus-book/db}"
DUMP="${1:-}"
if [ -z "$DUMP" ]; then
  DUMP="$(ls -1t "$DEST"/gnexus_book_*.dump 2>/dev/null | head -1 || true)"
fi
if [ -z "$DUMP" ] || [ ! -f "$DUMP" ]; then
  echo "Dump not found; pass a dump path or set GNEXUS_BOOK_BACKUP_DIR" >&2
  exit 2
fi

read -r MAINT_PG_URL TEMP_PG_URL TEMP_APP_URL TEMP_DB <<<"$(
  DB_URL="$DB_URL" "$REPO_ROOT/server/.venv/bin/python" - <<'PY'
import os
from datetime import datetime
from sqlalchemy.engine.url import make_url

url = make_url(os.environ["DB_URL"])
name = "gnexus_book_restore_" + datetime.now().strftime("%Y%m%d_%H%M%S") + "_" + str(os.getpid())
maintenance = url.set(database="postgres")
temp = url.set(database=name)


def pg(value):
    return value.render_as_string(hide_password=False).replace(
        "postgresql+psycopg", "postgresql"
    )


print(pg(maintenance), pg(temp), temp.render_as_string(hide_password=False), name)
PY
)"

CREATED=0
cleanup() {
  status=$?
  trap - EXIT
  if [ "$CREATED" = "1" ]; then
    psql "$MAINT_PG_URL" -v ON_ERROR_STOP=1 \
      -c "DROP DATABASE IF EXISTS \"$TEMP_DB\" WITH (FORCE)" >/dev/null 2>&1 || true
  fi
  if [ "$status" -ne 0 ] && [ -n "${SYNAPSE_URL:-}" ] && [ -n "${SYNAPSE_API_KEY:-}" ]; then
    "$SCRIPT_DIR/notify-synapse.sh" \
      "Gnexus Book restore drill failed" \
      "restore.failed" \
      "restore-drill.sh exited with $status for $(basename "$DUMP") on $(hostname)" \
      "high" >/dev/null 2>&1 || true
  fi
  exit "$status"
}
trap cleanup EXIT

pg_restore --list "$DUMP" >/dev/null
psql "$MAINT_PG_URL" -v ON_ERROR_STOP=1 -c "CREATE DATABASE \"$TEMP_DB\"" >/dev/null
CREATED=1
pg_restore --no-owner --no-acl --dbname "$TEMP_PG_URL" "$DUMP"

cd "$REPO_ROOT/server"
GNEXUS_BOOK_STORAGE_BACKEND=db \
GNEXUS_BOOK_DATABASE_URL="$TEMP_APP_URL" \
.venv/bin/python - <<'PY'
import os
import sys

from app.storage.db import Database
from app.storage.importer import database_counts
from app.storage.validation import validate_database

database = Database(os.environ["GNEXUS_BOOK_DATABASE_URL"])
counts = database_counts(database)
validation = validate_database(database)
print(
    "documents={documents} inventory_items={inventory_items} validation={validation}".format(
        documents=counts["documents"],
        inventory_items=counts["inventory_items"],
        validation=validation["status"],
    )
)
if counts["documents"] == 0 or validation["status"] != "ok":
    sys.exit(1)
PY

echo "restore drill ok: $(basename "$DUMP")"
