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

BACKUP_DIR="${BACKUP_DIR:-./backups}"
MYSQL_HOST="${MYSQL_HOST:-127.0.0.1}"
MYSQL_PORT="${MYSQL_PORT:-3307}"
MYSQL_USER="${MYSQL_USER:-ai_kb}"
MYSQL_PASSWORD="${MYSQL_PASSWORD:-ai_kb}"
MYSQL_DATABASE="${MYSQL_DATABASE:-ai_knowledge_base_v2}"

mkdir -p "$BACKUP_DIR"
OUTPUT_FILE="$BACKUP_DIR/${MYSQL_DATABASE}_$(date +%Y%m%d_%H%M%S).sql"

mysqldump \
  -h "$MYSQL_HOST" \
  -P "$MYSQL_PORT" \
  -u "$MYSQL_USER" \
  -p"$MYSQL_PASSWORD" \
  --single-transaction \
  --routines \
  --triggers \
  "$MYSQL_DATABASE" > "$OUTPUT_FILE"

echo "备份完成：$OUTPUT_FILE"
