#!/usr/bin/env bash
# restore.sh — restore a backup file to a service
# Usage: just restore supabase backups/postgres-20240101T030000Z.dump.gz
#
# WARNING: This is destructive. It will drop and re-create the database.
# Only run on a stopped or isolated instance.

set -euo pipefail

SERVICE="${1:?Usage: restore.sh <service> <file>}"
FILE="${2:?Usage: restore.sh <service> <file>}"

if [ ! -f "$FILE" ]; then
  echo "File not found: $FILE" >&2
  exit 1
fi

COMPOSE="docker compose -f $(dirname "$0")/../docker-compose.prod.yml"

case "$SERVICE" in
  supabase|postgres|db)
    echo "==> Restoring PostgreSQL from $FILE"
    echo "    WARNING: This will overwrite all data. Press Ctrl-C within 5s to abort."
    sleep 5

    if [[ "$FILE" == *.gz ]]; then
      gunzip -c "$FILE" | $COMPOSE exec -T db psql -U postgres
    else
      $COMPOSE exec -T db psql -U postgres < "$FILE"
    fi
    echo "==> Restore complete"
    ;;
  *)
    echo "Unknown service: $SERVICE. Use 'supabase'." >&2
    exit 1
    ;;
esac
