#!/usr/bin/env bash
set -euo pipefail

if [ $# -ne 1 ]; then
  echo "用法:"
  echo "  scripts/restore-db.sh ./backups/davos-assessment-YYYYMMDD-HHMMSS.dump"
  echo "  scripts/restore-db.sh ./backups/davos-assessment-YYYYMMDD-HHMMSS.sql.gz"
  exit 1
fi

PROJECT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
BACKUP_FILE="$1"
COMPOSE_FILE="${COMPOSE_FILE:-$PROJECT_DIR/docker-compose.yml}"
DB_SERVICE="${DB_SERVICE:-db}"
DATABASE="${POSTGRES_DB:-davos_assessment}"
USER="${POSTGRES_USER:-davos}"

if [ ! -f "$BACKUP_FILE" ]; then
  echo "找不到备份文件：$BACKUP_FILE"
  exit 1
fi

cd "$PROJECT_DIR"

case "$BACKUP_FILE" in
  *.dump)
    docker compose -f "$COMPOSE_FILE" exec -T "$DB_SERVICE" \
      sh -lc "dropdb -U \"$USER\" --if-exists \"$DATABASE\" && createdb -U \"$USER\" \"$DATABASE\""
    cat "$BACKUP_FILE" | docker compose -f "$COMPOSE_FILE" exec -T "$DB_SERVICE" \
      pg_restore -U "$USER" -d "$DATABASE" --clean --if-exists
    ;;
  *.sql.gz)
    gunzip -c "$BACKUP_FILE" | docker compose -f "$COMPOSE_FILE" exec -T "$DB_SERVICE" \
      psql -U "$USER" "$DATABASE"
    ;;
  *)
    echo "不支持的备份格式：$BACKUP_FILE"
    exit 1
    ;;
esac

echo "数据库恢复完成：$BACKUP_FILE"
