#!/usr/bin/env bash
# Restore an encrypted backup into a SEPARATE database and check it, without
# touching production. This is the restore drill. Run it monthly.
#
#   bash scripts/restore.sh backups/meatbrand-20261202T031500Z.dump.enc
#
# To actually replace production after a disaster, see docs/OPERATIONS.md.
set -euo pipefail
cd "$(dirname "$0")/.."
set -a; source .env; set +a
FILE=${1:?usage: restore.sh <backup file>}
TARGET=restore_drill

docker compose exec -T postgres psql -U "$POSTGRES_USER" -d postgres -q -c "DROP DATABASE IF EXISTS $TARGET" -c "CREATE DATABASE $TARGET"
openssl enc -d -aes-256-cbc -pbkdf2 -iter 200000 -pass env:BACKUP_PASSPHRASE -in "$FILE" \
  | docker compose exec -T postgres pg_restore -U "$POSTGRES_USER" -d "$TARGET" --no-owner --exit-on-error

echo "Restored into '$TARGET'. Row counts:"
docker compose exec -T postgres psql -U "$POSTGRES_USER" -d "$TARGET" -c \
  "select (select count(*) from businesses) businesses, (select count(*) from sites) sites, (select count(*) from products) products, (select count(*) from users) users, (select max(created_at) from audit_logs) latest_audit"
echo "Drill OK. Drop it with: docker compose exec postgres psql -U $POSTGRES_USER -d postgres -c 'DROP DATABASE $TARGET'"
