#!/bin/bash
# ============================================
# 服务器部署脚本 - 同步前端 + 构建 Java + 启动
# ============================================
set -e

# ==================== 1. 核心路径配置 ====================
PROJECT_DIR="/www/wwwroot/monisuo"           # 源码目录
BACKEND_DIR="/www/wwwroot"                   # 后端运行目录
FLUTTER_WEB_DIR="/www/wwwroot/monisuo-h5"    # Flutter Web 目录
ADMIN_DIR="/www/wwwroot/monisuo-admin"       # Vue Admin 目录

BACKEND_JAR_NAME="monisuo-1.0.jar"
BACKEND_PORT="5010"
BUILD_LOG="/tmp/monisuo_build_$(date +%Y%m%d).log"

# ==================== 2. 环境配置 ====================
export JAVA_HOME="/www/server/java/jdk1.8.0_371"
export PATH=$JAVA_HOME/bin:$PATH

# Maven 配置
MVN_EXEC=$(which mvn || find /www/server -name "mvn" | head -n 1 || echo "mvn")
export MAVEN_OPTS="-Xms512m -Xmx1024m"

# Maven 本地仓库
MAVEN_REPO="$PROJECT_DIR/.m2_repo"
mkdir -p $MAVEN_REPO && chmod -R 777 $MAVEN_REPO

# ==================== 3. 工具函数 ====================
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a $BUILD_LOG
}

# ==================== 4. 同步前端文件 ====================
sync_frontend() {
    log "📂 [前端] 同步文件..."

    # Flutter Web
    FLUTTER_BUILD_DIR="$PROJECT_DIR/flutter_monisuo/build/web"
    if [ -d "$FLUTTER_BUILD_DIR" ]; then
        log "4.1 同步 Flutter Web..."
        mkdir -p $FLUTTER_WEB_DIR
        rm -rf $FLUTTER_WEB_DIR/*
        cp -r $FLUTTER_BUILD_DIR/* $FLUTTER_WEB_DIR/
        log "✅ Flutter Web 同步完成"
    else
        log "⚠️ 未找到 Flutter 构建文件，跳过"
    fi

    # Vue Admin
    ADMIN_BUILD_DIR="$PROJECT_DIR/monisuo-admin/dist"
    if [ -d "$ADMIN_BUILD_DIR" ]; then
        log "4.2 同步 Vue Admin..."
        mkdir -p $ADMIN_DIR
        rm -rf $ADMIN_DIR/*
        cp -r $ADMIN_BUILD_DIR/* $ADMIN_DIR/
        log "✅ Vue Admin 同步完成"
    else
        log "⚠️ 未找到 Vue Admin 构建文件，跳过"
    fi
}

# ==================== 5. 后端构建与部署 ====================
deploy_backend() {
    log "🚀 [后端] 开始部署..."
    cd $PROJECT_DIR

    log "5.1 同步代码..."
    git fetch origin
    git reset --hard origin/main

    log "5.2 Maven 构建..."
    $MVN_EXEC clean package -DskipTests -Dmaven.repo.local=$MAVEN_REPO >> $BUILD_LOG 2>&1

    log "5.3 停止旧进程..."
    OLD_PID=$(ps -ef | grep "$BACKEND_JAR_NAME" | grep -v "grep" | awk '{print $2}')
    [ -z "$OLD_PID" ] || kill -9 $OLD_PID
    sleep 2

    log "5.4 部署 JAR 包..."
    SOURCE_JAR="$PROJECT_DIR/target/$BACKEND_JAR_NAME"
    if [ ! -f "$SOURCE_JAR" ]; then
        log "❌ 构建失败：未找到 $SOURCE_JAR"
        exit 1
    fi

    mkdir -p $BACKEND_DIR/logs
    cp -f "$SOURCE_JAR" "$BACKEND_DIR/"

    log "5.5 启动服务..."
    cd $BACKEND_DIR
    nohup $JAVA_HOME/bin/java -Xms512m -Xmx1024m -jar $BACKEND_JAR_NAME --spring.profiles.active=prd --server.port=$BACKEND_PORT > ./logs/console.log 2>&1 &
    log "✅ 后端启动成功 (PID: $!)"
}

# ==================== 6. 执行主流程 ====================
case "$1" in
    frontend)
        sync_frontend
        ;;
    backend)
        deploy_backend
        ;;
    *)
        sync_frontend
        deploy_backend
        ;;
esac

log "🏁 [$(date '+%H:%M:%S')] 部署完成！"
