#!/bin/bash
# 简化版自动部署脚本 - 直接运行源码

set -e

DEPLOY_LOG="/tmp/deploy-simple.log"
PROJECT_DIR="/data/ai/audio_codebuddy"
FRONTEND_PORT="5173"
BACKEND_PORT="3100"

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

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

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

# Git pull (冲突时强制用仓库版本)
log "执行 git pull..."
cd "$PROJECT_DIR"
git fetch origin
git reset --hard origin/master 2>&1 | tee -a "$DEPLOY_LOG"

# ========== 启动/重启前端 ==========
log "启动前端 dev server..."
cd "$PROJECT_DIR/my-uniapp-vue3"

# 停止旧的前端进程
pkill -f "vite" 2>/dev/null || true
pm2 delete frontend 2>/dev/null || true

# 安装依赖
npm install 2>&1 | tee -a "$DEPLOY_LOG"

# 后台启动前端 dev server (监听所有网卡)
nohup npx vite --host 0.0.0.0 --port $FRONTEND_PORT > "$DEPLOY_LOG.frontend.log" 2>&1 &
FRONTEND_PID=$!
echo "Frontend PID: $FRONTEND_PID"
sleep 8  # 等待启动

log "前端启动完成 (PID: $FRONTEND_PID)"

# ========== 启动/重启后端 ==========
log "启动后端服务..."
cd "$PROJECT_DIR/server"

# 安装依赖
npm install 2>&1 | tee -a "$DEPLOY_LOG"

# 停止旧的后端进程
pm2 delete server 2>/dev/null || true

# 编译 TypeScript
npm run build 2>&1 | tee -a "$DEPLOY_LOG"

# 使用编译后的 JS 运行
SERVER_PORT=$BACKEND_PORT pm2 start dist/app.js --name server 2>&1 | tee -a "$DEPLOY_LOG"

pm2 save 2>&1 | tee -a "$DEPLOY_LOG"

log "========== 部署完成 =========="
log "前端: http://localhost:$FRONTEND_PORT"
log "后端: http://localhost:$BACKEND_PORT"
