#!/usr/bin/env bash
# mBlog — rehearse the Module 1 migration on a throwaway copy of production.
# Proves it applies cleanly, is idempotent, verifies, and reverses — WITHOUT
# touching the live database. Run this before applying the migration for real.
#
# Usage:
#   PG_SUPERUSER=postgres ./rehearse-migration.sh backups/db-YYYYmmdd-HHMMSS.sql.gz [module1-dir]
set -euo pipefail

DUMP="${1:?usage: rehearse-migration.sh <db-dump.sql.gz> [module1-dir]}"
MIG_DIR="${2:-./mblog_module1}"
DB_HOST="${MBLOG_DB_HOST:-127.0.0.1}"
DB_PORT="${MBLOG_DB_PORT:-5432}"
SUPER="${PG_SUPERUSER:-postgres}"
SCRATCH="mblog_rehearse_$(date +%s)"

psql -h "$DB_HOST" -p "$DB_PORT" -U "$SUPER" -c "CREATE DATABASE ${SCRATCH};"
trap 'psql -h "$DB_HOST" -p "$DB_PORT" -U "$SUPER" -c "DROP DATABASE IF EXISTS ${SCRATCH};" >/dev/null 2>&1 || true' EXIT

run() { psql -v ON_ERROR_STOP=1 -q -h "$DB_HOST" -p "$DB_PORT" -U "$SUPER" "$SCRATCH" -f "$1"; }

echo "==> Restoring production dump into scratch DB '${SCRATCH}'"
gunzip -c "$DUMP" | psql -q -h "$DB_HOST" -p "$DB_PORT" -U "$SUPER" "$SCRATCH" >/dev/null

echo "==> Apply migration (up)";                 run "$MIG_DIR/001_module1_core_alignment.up.sql"
echo "==> Re-apply (must be a no-op / idempotent)"; run "$MIG_DIR/001_module1_core_alignment.up.sql"
echo "==> Verify";                                run "$MIG_DIR/001_verify.sql"
echo "==> Roll back (down)";                      run "$MIG_DIR/001_module1_core_alignment.down.sql"
echo "==> Re-apply after rollback";               run "$MIG_DIR/001_module1_core_alignment.up.sql"

echo
echo "REHEARSAL OK — migration is clean, idempotent and reversible on a copy of production."
echo "The scratch database will be dropped automatically."
