#!/bin/bash
# MySQL 恢复脚本（Linux 容器内运行）
# 用法: restore-mysql.sh --service <name> --file <path> [--yes]
set -euo pipefail

# ---------- 参数解析 ----------
SERVICE=""
BACKUP_FILE=""
ASSUME_YES=false

while [[ $# -gt 0 ]]; do
  case "$1" in
    --service)
      SERVICE="${2:-}"
      shift 2
      ;;
    --file)
      BACKUP_FILE="${2:-}"
      shift 2
      ;;
    --yes)
      ASSUME_YES=true
      shift
      ;;
    -h|--help)
      echo "Usage: $0 --service <name> --file <path> [--yes]" >&2
      echo "  --service  目标微服务数据库名（必填）" >&2
      echo "  --file     备份文件路径 sql.gz（必填）" >&2
      echo "  --yes      跳过确认提示" >&2
      exit 0
      ;;
    *)
      echo "[ERROR] 未知参数: $1" >&2
      exit 1
      ;;
  esac
done

# ---------- 参数校验 ----------
if [[ -z "$SERVICE" ]]; then
  echo "[ERROR] --service 参数必填" >&2
  exit 1
fi

if [[ -z "$BACKUP_FILE" ]]; then
  echo "[ERROR] --file 参数必填" >&2
  exit 1
fi

if [[ ! -f "$BACKUP_FILE" ]]; then
  echo "[ERROR] 备份文件不存在: ${BACKUP_FILE}" >&2
  exit 1
fi

# ---------- 环境变量 ----------
: "${MYSQL_HOST:=mysql}"
: "${MYSQL_PORT:=3306}"
: "${MYSQL_USER:=root}"
: "${MYSQL_PASSWORD:?MYSQL_PASSWORD 环境变量未设置}"

# ---------- 日志函数 ----------
log() {
  echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" >&2
}

# ---------- 确认提示 ----------
log "[WARN] 即将向数据库 [${SERVICE}] 导入备份文件: ${BACKUP_FILE}"
log "[WARN] 此操作会覆盖目标数据库现有数据，不可撤销！"

if [[ "$ASSUME_YES" != "true" ]]; then
  read -r -p "确认继续? (输入 YES 继续): " confirm
  if [[ "$confirm" != "YES" ]]; then
    log "[INFO] 用户取消操作"
    exit 0
  fi
fi

# ---------- 主流程 ----------
log "[INFO] 开始恢复服务: ${SERVICE}"

log "[INFO] 解压并导入: ${BACKUP_FILE}"
if ! gunzip -c "$BACKUP_FILE" \
    | mysql \
        --host="$MYSQL_HOST" \
        --port="$MYSQL_PORT" \
        --user="$MYSQL_USER" \
        --password="$MYSQL_PASSWORD" \
        "$SERVICE"; then
  log "[ERROR] mysql 导入失败 (service=${SERVICE})"
  exit 1
fi

log "[INFO] 恢复完成: ${SERVICE} <- ${BACKUP_FILE}"
exit 0
