#!/bin/bash
# 自动部署脚本 - 由 webhook 触发

set -e

DEPLOY_LOG="/tmp/deploy-auto.log"
PROJECT_DIR="/data/ai/audio_codebuddy"
BACKEND_PORT="3100"
FRONTEND_DIR="/data/ai/audio/frontend"

log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$DEPLOY_LOG"
}

log "========== 开始自动部署 =========="

# 切换到项目目录
cd "$PROJECT_DIR"

# Git pull
log "执行 git pull..."
git pull origin master 2>&1 | tee -a "$DEPLOY_LOG"

# ========== 构建前端 ==========
log "构建前端..."
cd "$PROJECT_DIR/my-uniapp-vue3"
npm install 2>&1 | tee -a "$DEPLOY_LOG"
npm run build:h5 2>&1 | tee -a "$DEPLOY_LOG"

# 复制前端文件到部署目录
log "部署前端..."
# 移除 immutable 属性（BT 面板的 .user.ini 是 immutable 的）
chattr -i "$FRONTEND_DIR/build/h5/.user.ini" 2>/dev/null || true
# 使用 rsync 同步文件，避免嵌套目录问题
rsync -a --delete "$PROJECT_DIR/my-uniapp-vue3/dist/build/h5/" "$FRONTEND_DIR/build/h5/"
log "前端部署完成"

# ========== 构建后端 ==========
log "构建后端..."
cd "$PROJECT_DIR/server"
npm install 2>&1 | tee -a "$DEPLOY_LOG"
npm run build 2>&1 | tee -a "$DEPLOY_LOG"
cp src/config/models.json dist/config/models.json 2>&1 | tee -a "$DEPLOY_LOG"

# 重启后端服务
log "重启后端服务..."

if command -v pm2 &> /dev/null; then
    pm2 delete server 2>/dev/null || true
    SERVER_PORT=3100 pm2 start dist/app.js --name server 2>&1 | tee -a "$DEPLOY_LOG"
    pm2 save 2>&1 | tee -a "$DEPLOY_LOG"
else
    log "PM2 未安装，跳过进程管理"
fi

log "========== 部署完成 =========="
