#!/bin/bash

# ============================================
# Monisuo CI/CD 部署脚本 - 宝塔 Webhook
# ============================================

# ============ 环境配置 ============
# JDK 路径（根据实际修改）
export JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk
export PATH=$JAVA_HOME/bin:$PATH

# Maven 路径（如果手动安装）
export MAVEN_HOME=/opt/maven
export PATH=$MAVEN_HOME/bin:$PATH

# ============ 项目配置 ============
PROJECT_PATH="/opt/monisuo"
GIT_REPO="http://sion:woshisaw.@8.155.172.147:3001/sion/monisuo.git"
JAR_NAME="monisuo-1.0.jar"
LOG_FILE="/opt/monisuo/deploy.log"
WEBHOOK_SECRET=""

# ============ 日志函数 ============
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" >> $LOG_FILE
}

# ============ 错误处理 ============
error_exit() {
    log "❌ 错误: $1"
    echo "Error: $1"
    exit 1
}

# ============ 主流程 ============
log "=========================================="
log "🚀 开始 CI/CD 部署"
log "=========================================="

# 记录环境信息
log "Java 版本: $(java -version 2>&1 | head -1)"
log "Maven 版本: $(mvn -version 2>&1 | head -1)"
log "当前目录: $(pwd)"

# 1. 检查/克隆项目
if [ ! -d "$PROJECT_PATH/.git" ]; then
    log "📥 首次部署，克隆项目..."
    mkdir -p $PROJECT_PATH
    git clone $GIT_REPO $PROJECT_PATH >> $LOG_FILE 2>&1 || error_exit "Git 克隆失败"
fi

cd $PROJECT_PATH || error_exit "无法进入项目目录"

# 2. 拉取最新代码
log "📥 拉取最新代码..."
git fetch origin >> $LOG_FILE 2>&1
git reset --hard origin/main >> $LOG_FILE 2>&1 || error_exit "Git 拉取失败"

# 获取提交信息
COMMIT_HASH=$(git rev-parse --short HEAD)
COMMIT_MSG=$(git log -1 --pretty=%s)
log "📝 最新提交: $COMMIT_HASH - $COMMIT_MSG"

# 3. 检查文件变更
CHANGED_FILES=$(git diff --name-only HEAD~1 HEAD 2>/dev/null)
log "📁 变更文件: $CHANGED_FILES"

# 4. 后端构建和部署
if echo "$CHANGED_FILES" | grep -qE "^src/|^pom.xml"; then
    log "🔨 检测到后端代码变更，开始构建..."

    cd $PROJECT_PATH
    mvn clean package -DskipTests >> $LOG_FILE 2>&1

    if [ $? -ne 0 ]; then
        error_exit "Maven 构建失败"
    fi
    log "✅ Maven 构建成功"
else
    log "⏭️ 后端代码无变更，跳过构建"
fi

# 5. 停止旧服务
log "🛑 停止旧服务..."
pkill -f $JAR_NAME 2>/dev/null
sleep 3

# 检查是否停止成功
if pgrep -f $JAR_NAME > /dev/null; then
    log "⚠️ 进程未停止，强制终止..."
    pkill -9 -f $JAR_NAME 2>/dev/null
    sleep 2
fi

# 6. 启动新服务
log "🚀 启动新服务..."
cd $PROJECT_PATH

nohup java -jar \
    -Xms256m \
    -Xmx512m \
    -XX:+UseG1GC \
    target/$JAR_NAME \
    --spring.profiles.active=dev \
    > $PROJECT_PATH/app.log 2>&1 &

# 7. 检查服务状态
sleep 5
if pgrep -f $JAR_NAME > /dev/null; then
    PID=$(pgrep -f $JAR_NAME)
    log "✅ 服务启动成功 (PID: $PID)"
else
    log "❌ 服务启动失败，查看日志:"
    tail -50 $PROJECT_PATH/app.log >> $LOG_FILE
    error_exit "服务启动失败"
fi

# 8. 健康检查
log "🔍 健康检查..."
sleep 5
HEALTH_CHECK=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:5010/ 2>/dev/null || echo "000")

if [ "$HEALTH_CHECK" = "200" ] || [ "$HEALTH_CHECK" = "404" ]; then
    log "✅ 健康检查通过 (HTTP $HEALTH_CHECK)"
else
    log "⚠️ 健康检查异常 (HTTP $HEALTH_CHECK)"
fi

# 9. 清理旧日志
log "🧹 清理旧日志..."
find $PROJECT_PATH -name "*.log" -mtime +7 -delete 2>/dev/null

# 10. 完成
log "=========================================="
log "✅ CI/CD 部署完成"
log "   提交: $COMMIT_HASH"
log "   时间: $(date '+%Y-%m-%d %H:%M:%S')"
log "=========================================="

echo "Deploy Success! Commit: $COMMIT_HASH"
