#!/usr/bin/env bash
# 恭学教育 — PM2 部署脚本
# 用法: ./deploy.sh [ssh_host]
set -euo pipefail

SSH_HOST="${1:-tencent}"
REMOTE_DIR="/opt/gongxue"

echo "=== 1/5 本地构建后端 ==="
npm run build -w @gongxue/server

echo "=== 2/5 本地构建前端 ==="
npm run build -w @gongxue/admin

echo "=== 3/5 同步到 ${SSH_HOST} ==="
rsync -avz --delete \
  --exclude='node_modules' \
  --exclude='.git' \
  --exclude='*.db' \
  --exclude='.DS_Store' \
  --exclude='logs/' \
  --exclude='.turbo/' \
  ./ "${SSH_HOST}:${REMOTE_DIR}/"

echo "=== 4/5 启动 MySQL + 安装依赖 ==="
ssh "${SSH_HOST}" "
  cd ${REMOTE_DIR}
  docker compose up -d mysql
  mkdir -p logs
  for i in \$(seq 1 30); do
    docker compose exec -T mysql mysqladmin ping -h localhost --silent 2>/dev/null && break
    echo '等待 MySQL...'
    sleep 2
  done
  if [ ! -d node_modules ]; then
    echo '首次部署，安装依赖...'
    npm ci --omit=dev
  fi
"

echo "=== 5/5 PM2 重载 ==="
ssh "${SSH_HOST}" "
  cd ${REMOTE_DIR}
  pm2 startOrReload ecosystem.config.cjs --update-env
  pm2 save
  pm2 status
"

echo ""
echo "部署完成！"
echo "访问: http://$(ssh "${SSH_HOST}" 'hostname -I 2>/dev/null | awk "{print \$1}" || curl -s ifconfig.me')"
echo ""
echo "══════ 首次部署/数据迁移 ══════"
echo "1) 上传旧数据库:"
echo "   scp ~/Downloads/dorm_billing_*.sql.gz ${SSH_HOST}:${REMOTE_DIR}/"
echo "2) 服务器上执行:"
echo "   ssh ${SSH_HOST}"
echo "   cd ${REMOTE_DIR}"
echo "   cp .env.example .env && vim .env        # 改密码"
echo "   sudo setcap 'cap_net_bind_service=+ep' \$(which node)"
echo "   ./migrate.sh dorm_billing_*.sql.gz        # 迁移旧数据"
