#!/bin/bash
# MySQL 数据库恢复脚本
# 用法: ./restore-db.sh <backup_file>

set -e

if [ -z "$1" ]; then
  echo "Usage: ./restore-db.sh <backup_file>"
  echo "Available backups:"
  ls -lh backups/db_backup_*.sql.gz 2>/dev/null
  exit 1
fi

BACKUP_FILE="$1"
DATABASE_URL="${DATABASE_URL:-}"

if [ -z "$DATABASE_URL" ]; then
  echo "ERROR: DATABASE_URL not set"
  exit 1
fi

# 解析 URL (同 backup-db.sh)
DB_USER=$(echo $DATABASE_URL | sed -n 's/.*:\/\/\([^:]*\):.*/\1/p')
DB_PASS=$(echo $DATABASE_URL | sed -n 's/.*:\/\/[^:]*:\([^@]*\)@.*/\1/p')
DB_HOST=$(echo $DATABASE_URL | sed -n 's/.*@\([^:]*\):.*/\1/p')
DB_PORT=$(echo $DATABASE_URL | sed -n 's/.*:\([0-9]*\)\/.*/\1/p')
DB_NAME=$(echo $DATABASE_URL | sed -n 's/.*\/\([^?]*\).*/\1/p')

echo "Restoring database: $DB_NAME from $BACKUP_FILE"

# 解压并恢复
gunzip -c "$BACKUP_FILE" | mysql -h "$DB_HOST" -P "$DB_PORT" -u "$DB_USER" -p"$DB_PASS" "$DB_NAME"

echo "Restore completed successfully."
