#!/usr/bin/env bash
# 恭学教育 — 数据迁移脚本（仅首次运行）
# 用法:
#   1. 确认 MySQL 已启动：docker compose up -d mysql
#   2. ./migrate.sh /path/to/dump.sql.gz
set -euo pipefail

DUMP="${1:-}"
if [ -z "$DUMP" ]; then
  echo "用法: ./migrate.sh /path/to/dump.sql.gz"
  echo "示例: ./migrate.sh ~/Downloads/dorm_billing_2026-07-06_01-30-02_mysql_data.sql.gz"
  exit 1
fi

# 从 .env 读取密码
MYSQL_PASS="${MYSQL_ROOT_PASSWORD:-gongxue_2024}"

echo "=== 1/4 导入旧 dump ==="
gunzip -c "$DUMP" | docker compose exec -T mysql mysql -u root -p"${MYSQL_PASS}" dorm_billing
echo "旧库导入完成: $(docker compose exec -T mysql mysql -u root -p"${MYSQL_PASS}" -e 'SELECT COUNT(*) AS cnt FROM dorm_billing.students' -N)"

echo "=== 2/4 启动应用（创建新表结构） ==="
# 短暂启动让 TypeORM synchronize 创建表，然后停掉
DB_SYNCHRONIZE=true pm2 start ecosystem.config.cjs --only gongxue-backend
sleep 8
pm2 stop gongxue-backend

echo "=== 3/4 执行数据迁移 ==="
docker compose exec -T mysql mysql -u root -p"${MYSQL_PASS}" < migrate-legacy.sql

echo "=== 4/4 重启应用 ==="
pm2 startOrReload ecosystem.config.cjs --update-env
pm2 save

echo ""
echo "迁移完成！运行以下验证:"
echo "  docker compose exec mysql mysql -u root -p${MYSQL_PASS} gongxue -e 'SELECT COUNT(*) FROM students'"
