#!/usr/bin/env bash
# Restore a verified bundle into a NEW test database, never over the active DB.
set -euo pipefail
umask 077
bundle=$(realpath "${1:?Usage: restore_database.sh BUNDLE ftg2_beta_restore_unique}")
target=${2:?Supply a NEW ftg2_beta_restore_* database}
[[ "$target" =~ ^ftg2_beta_restore_[a-z0-9_]+$ && ${#target} -le 63 ]] || { echo 'Unsafe restore database name' >&2; exit 2; }
(cd "$bundle"; sha256sum --check SHA256SUMS)
cd "$(dirname "$(realpath "$0")")"
compose=(docker compose --env-file .env.server -f compose.yaml)
exists=$("${compose[@]}" exec -T -e FTG_RESTORE_DB="$target" db sh -ec 'test "$FTG_RESTORE_DB" != "$POSTGRES_DB"; exec psql -U "$POSTGRES_USER" -d postgres -v target="$FTG_RESTORE_DB" -At' <<'SQL'
SELECT 1 FROM pg_database WHERE datname=:'target';
SQL
)
test -z "$exists" || { echo 'Restore target already exists; refusing' >&2; exit 2; }
"${compose[@]}" exec -T -e FTG_RESTORE_DB="$target" db sh -ec 'createdb -U "$POSTGRES_USER" "$FTG_RESTORE_DB"'
"${compose[@]}" exec -T -e FTG_RESTORE_DB="$target" db sh -ec 'pg_restore -U "$POSTGRES_USER" -d "$FTG_RESTORE_DB" --exit-on-error --single-transaction --no-owner --no-privileges' < "$bundle/database.dump"
echo "Restored to isolated database $target. Active web DB unchanged."
echo 'Next: restore private media and Redis into separate NEW volumes, then run checks and compare table hashes before switching traffic.'
