#!/usr/bin/env bash
set -euo pipefail

if [ "$#" -ne 1 ] || [ ! -f "$1" ]; then
  echo "Usage: $0 /absolute/path/to/cnc_eval_db.backup"
  exit 2
fi
if [ "${CONFIRM_RESTORE:-}" != "cnc_eval_db" ]; then
  echo "Restore blocked. Set CONFIRM_RESTORE=cnc_eval_db to confirm replacement."
  exit 3
fi
COMPOSE_PROJECT_NAME="${COMPOSE_PROJECT_NAME:-cnc_precision}"

docker compose -p "$COMPOSE_PROJECT_NAME" exec -T db pg_restore --list <"$1" >/dev/null
docker compose -p "$COMPOSE_PROJECT_NAME" exec -T db dropdb -U "${POSTGRES_USER:-precision}" --if-exists --force cnc_eval_db
docker compose -p "$COMPOSE_PROJECT_NAME" exec -T db createdb -U "${POSTGRES_USER:-precision}" -T template0 cnc_eval_db
docker compose -p "$COMPOSE_PROJECT_NAME" exec -T db pg_restore -U "${POSTGRES_USER:-precision}" -d cnc_eval_db --no-owner --exit-on-error <"$1"
docker compose -p "$COMPOSE_PROJECT_NAME" exec -T db psql -U "${POSTGRES_USER:-precision}" -d cnc_eval_db -c 'ANALYZE;'
echo "Restore completed: cnc_eval_db"
