#!/bin/bash

# 增强版 Jenkins 监控脚本

JENKINS_SCRIPT="/opt/jenkins/jenkins.sh"
LOG_FILE="/opt/jenkins/jenkins_monitor.log"
MAX_RETRIES=3
RETRY_DELAY=10

current_time() {
    echo "$(date '+%Y-%m-%d %H:%M:%S')"
}

check_jenkins() {
    if $JENKINS_SCRIPT status > /dev/null 2>&1; then
        # 获取进程信息用于详细日志
        if [ -f "/opt/jenkins/jenkins.pid" ]; then
            PID=$(cat "/opt/jenkins/jenkins.pid")
            if ps -p "$PID" > /dev/null; then
                echo "$(current_time) - Jenkins 运行正常 (PID: $PID)" >> "$LOG_FILE"
                return 0
            fi
        fi
    fi
    return 1
}

start_jenkins_with_retry() {
    local retries=0
    
    while [ $retries -lt $MAX_RETRIES ]; do
        echo "$(current_time) - 尝试启动 Jenkins (尝试 $((retries+1))/$MAX_RETRIES)..." >> "$LOG_FILE"
        
        $JENKINS_SCRIPT start >> "$LOG_FILE" 2>&1
        sleep $RETRY_DELAY
        
        if check_jenkins; then
            echo "$(current_time) - Jenkins 启动成功" >> "$LOG_FILE"
            return 0
        fi
        
        retries=$((retries+1))
        sleep 5
    done
    
    echo "$(current_time) - 错误: 经过 $MAX_RETRIES 次尝试后仍无法启动 Jenkins" >> "$LOG_FILE"
    return 1
}

main() {
    echo "$(current_time) ===== Jenkins 监控检查开始 =====" >> "$LOG_FILE"
    
    if check_jenkins; then
        echo "$(current_time) - 状态: 正常运行" >> "$LOG_FILE"
    else
        echo "$(current_time) - 状态: 未运行" >> "$LOG_FILE"
        start_jenkins_with_retry
    fi
    
    echo "$(current_time) ===== Jenkins 监控检查完成 =====" >> "$LOG_FILE"
    echo "----------------------------------------" >> "$LOG_FILE"
}

main
