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

MYSQL_HOST="${MYSQL_HOST:-127.0.0.1}"
MYSQL_PORT="${MYSQL_PORT:-3307}"
MYSQL_USER="${MYSQL_USER:-ai_kb}"
MYSQL_DATABASE="${MYSQL_DATABASE:-ai_knowledge_base_v2}"
: "${MYSQL_PASSWORD:?必须通过 MYSQL_PASSWORD 配置数据库密码}"
: "${BACKUP_FILE:?必须通过 BACKUP_FILE 指定 .sql.gz 备份文件}"

if [[ "${RESTORE_CONFIRM:-}" != "YES" ]]; then
  echo "恢复会覆盖目标数据库数据，确认后请设置 RESTORE_CONFIRM=YES" >&2
  exit 2
fi

command -v mysql >/dev/null || { echo "未找到 mysql 客户端" >&2; exit 1; }
command -v gzip >/dev/null || { echo "未找到 gzip" >&2; exit 1; }
if command -v sha256sum >/dev/null; then
  checksum_command=(sha256sum -c)
elif command -v shasum >/dev/null; then
  checksum_command=(shasum -a 256 -c)
else
  echo "未找到 sha256sum 或 shasum" >&2
  exit 1
fi
test -f "$BACKUP_FILE" || { echo "备份文件不存在：$BACKUP_FILE" >&2; exit 1; }
test -f "${BACKUP_FILE}.sha256" || { echo "缺少校验文件：${BACKUP_FILE}.sha256" >&2; exit 1; }

(cd "$(dirname "$BACKUP_FILE")" && "${checksum_command[@]}" "$(basename "$BACKUP_FILE").sha256")
gzip -t "$BACKUP_FILE"

MYSQL_PWD="$MYSQL_PASSWORD" gzip -dc "$BACKUP_FILE" | MYSQL_PWD="$MYSQL_PASSWORD" mysql \
  --host="$MYSQL_HOST" \
  --port="$MYSQL_PORT" \
  --user="$MYSQL_USER" \
  --default-character-set=utf8mb4 \
  "$MYSQL_DATABASE"

MYSQL_PWD="$MYSQL_PASSWORD" mysql \
  --host="$MYSQL_HOST" \
  --port="$MYSQL_PORT" \
  --user="$MYSQL_USER" \
  --database="$MYSQL_DATABASE" \
  --batch --skip-column-names \
  --execute="SELECT CONCAT('恢复完成，迁移版本：', COALESCE((SELECT version_num FROM alembic_version LIMIT 1), '未知'));"
