#!/usr/bin/env bash
# 从本机 MySQL 导出完整数据（含询价记录）
# 用法：bash deploy/database/export-local.sh
# 依赖：mysqldump、项目根目录 .env

set -euo pipefail
ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
OUT_DIR="${ROOT}/deploy/database"
STAMP="$(date +%Y%m%d-%H%M%S)"
OUT_FILE="${OUT_DIR}/chajia-full-${STAMP}.sql"

if [[ ! -f "${ROOT}/.env" ]]; then
  echo "缺少 ${ROOT}/.env"
  exit 1
fi

# shellcheck disable=SC1090
set -a
source "${ROOT}/.env"
set +a

if [[ -z "${DATABASE_URL:-}" ]]; then
  echo ".env 中未设置 DATABASE_URL"
  exit 1
fi

if ! command -v mysqldump >/dev/null 2>&1; then
  echo "未找到 mysqldump，请安装 MySQL 客户端"
  exit 1
fi

# 解析 mysql://user:pass@host:port/db
if [[ ! "$DATABASE_URL" =~ mysql://([^:]+):([^@]+)@([^:/]+):?([0-9]*)/([^?]+) ]]; then
  echo "无法解析 DATABASE_URL: $DATABASE_URL"
  exit 1
fi

DB_USER="${BASH_REMATCH[1]}"
DB_PASS="${BASH_REMATCH[2]}"
DB_HOST="${BASH_REMATCH[3]}"
DB_PORT="${BASH_REMATCH[4]:-3306}"
DB_NAME="${BASH_REMATCH[5]}"

mkdir -p "$OUT_DIR"

mysqldump \
  -h "$DB_HOST" \
 -P "$DB_PORT" \
  -u "$DB_USER" \
  -p"$DB_PASS" \
  --default-character-set=utf8mb4 \
  --single-transaction \
  --routines \
  --triggers \
  --set-gtid-purged=OFF \
  "$DB_NAME" > "$OUT_FILE"

gzip -kf "$OUT_FILE"
echo "已导出: ${OUT_FILE}"
echo "已压缩: ${OUT_FILE}.gz"
