#!/usr/bin/env bash
# Restore a local pg_dump backup to the remote swym database.
#
# Usage: ./script/database-restore.sh <backup_path>
#
# backup_path  Local pg_dump custom-format file produced by database-backup.sh.
#
# WARNING: This will DROP and recreate all objects in the target database.
#          All swym services on the app host will be stopped during the restore
#          and restarted afterwards.
set -euo pipefail

REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"

SSH_USER="grenade"
APP_HOST="quadbrat.hanzalova.internal"
SERVICES=(swym-api swym-ingest-binance swym-market-worker swym-paper-executor)

if [[ $# -lt 1 ]]; then
    echo "Usage: $0 <backup_path>" >&2
    exit 1
fi

backup_path="$1"

if [[ ! -f "$backup_path" ]]; then
    echo "Error: backup file not found: $backup_path" >&2
    exit 1
fi

# Build connection string from dev api config (same logic as seed-dev.sh).
api_cfg="$REPO_ROOT/config/dev/api.json"
config_db_url=$(jq -r '.database.url' "$api_cfg")
db_user="$(echo "${config_db_url}" | cut -d '/' -f 3 | cut -d '@' -f 1)"
db_host="$(echo "${config_db_url}" | cut -d '@' -f 2 | cut -d ':' -f 1)"
db_port="$(echo "${config_db_url}" | cut -d ':' -f 3 | cut -d '/' -f 1)"
db_name="$(echo "${config_db_url}" | cut -d '/' -f 4 | cut -d '?' -f 1)"
db_ssl_mode=verify-full
db_ssl_root_cert=/etc/pki/ca-trust/source/anchors/ca.internal-rsa.pem
db_ssl_cert=/etc/pki/tls/misc/$(hostnamectl hostname)-rsa.pem
db_ssl_key=/etc/pki/tls/private/$(hostnamectl hostname)-rsa.pem
db_url="postgres://${db_user}@${db_host}:${db_port}/${db_name}?sslmode=${db_ssl_mode}&sslrootcert=${db_ssl_root_cert}&sslcert=${db_ssl_cert}&sslkey=${db_ssl_key}"

backup_size=$(du -sh "$backup_path" | cut -f1)

echo "╔══════════════════════════════════════════════════════════════╗"
echo "║                  DATABASE RESTORE WARNING                    ║"
echo "╠══════════════════════════════════════════════════════════════╣"
echo "  Backup file : $backup_path ($backup_size)"
echo "  Target DB   : ${db_user}@${db_host}:${db_port}/${db_name}"
echo "  App host    : ${APP_HOST}"
echo ""
echo "  This will DROP and recreate ALL objects in the target database."
echo "  All swym services will be stopped and restarted."
echo "╚══════════════════════════════════════════════════════════════╝"
echo ""
read -r -p "Type 'yes' to proceed: " confirm
if [[ "$confirm" != "yes" ]]; then
    echo "Aborted."
    exit 1
fi

# Ensure services are restarted even if the restore fails.
restart_services() {
    echo "==> Restarting swym services on ${APP_HOST}..."
    for svc in "${SERVICES[@]}"; do
        ssh "${SSH_USER}@${APP_HOST}" sudo systemctl start "$svc" || \
            echo "  Warning: failed to start ${svc} (may already be running or not installed)"
    done
    echo "==> Services restarted."
}
trap restart_services EXIT

echo "==> Stopping swym services on ${APP_HOST}..."
for svc in "${SERVICES[@]}"; do
    ssh "${SSH_USER}@${APP_HOST}" sudo systemctl stop "$svc" || true
done
echo "==> Services stopped."

echo "==> Restoring ${backup_path} → ${db_user}@${db_host}:${db_port}/${db_name}..."

pg_restore \
    --clean \
    --if-exists \
    --no-password \
    --dbname="$db_url" \
    "$backup_path"

echo "==> Restore complete at $(date -u '+%Y-%m-%dT%H:%M:%SZ')"
