#!/usr/bin/env bash

set -euo pipefail

SRC_DB="${SRC_DB:-giteadb}"
SRC_USER="${SRC_USER:-gitea}"
SRC_PASSWORD="${SRC_PASSWORD:-}"
DST_DB="${DST_DB:-quantenginedb}"
DST_USER="${DST_USER:-quantengine_app}"
DST_PASSWORD="${DST_PASSWORD:-}"
HOST="${HOST:-127.0.0.1}"
PORT="${PORT:-5432}"
SCHEMA="${SCHEMA:-quantengine}"

if [ -z "${SRC_PASSWORD}" ] || [ -z "${DST_PASSWORD}" ]; then
    echo "ERROR: SRC_PASSWORD and DST_PASSWORD must be set."
    exit 1
fi

TMP_DIR="$(mktemp -d)"
trap 'rm -rf "${TMP_DIR}"' EXIT

echo "[1/4] Dumping ${SCHEMA} from ${SRC_DB}..."
PGPASSWORD="${SRC_PASSWORD}" pg_dump -h "${HOST}" -p "${PORT}" -U "${SRC_USER}" -n "${SCHEMA}" --no-owner --no-privileges "${SRC_DB}" > "${TMP_DIR}/quantengine_schema.sql"
grep -vE '^CREATE SCHEMA ' "${TMP_DIR}/quantengine_schema.sql" > "${TMP_DIR}/quantengine_schema.filtered.sql"

echo "[2/4] Ensuring destination schema exists..."
PGPASSWORD="${DST_PASSWORD}" psql -h "${HOST}" -p "${PORT}" -U "${DST_USER}" -d "${DST_DB}" -v ON_ERROR_STOP=1 <<SQL
CREATE SCHEMA IF NOT EXISTS ${SCHEMA} AUTHORIZATION ${DST_USER};
ALTER SCHEMA ${SCHEMA} OWNER TO ${DST_USER};
SQL

echo "[3/4] Restoring into ${DST_DB}..."
PGPASSWORD="${DST_PASSWORD}" psql -h "${HOST}" -p "${PORT}" -U "${DST_USER}" -d "${DST_DB}" -v ON_ERROR_STOP=1 -f "${TMP_DIR}/quantengine_schema.filtered.sql"

echo "[4/4] Verifying restore..."
PGPASSWORD="${DST_PASSWORD}" psql -h "${HOST}" -p "${PORT}" -U "${DST_USER}" -d "${DST_DB}" -Atc "SELECT schemaname || '.' || tablename FROM pg_tables WHERE schemaname = '${SCHEMA}' ORDER BY tablename;"

echo "Migration completed: ${SRC_DB}.${SCHEMA} -> ${DST_DB}.${SCHEMA}"
