#!/bin/bash

# Jenkins 控制脚本
# 使用方法: ./jenkins.sh {start|stop|restart|status}

JENKINS_WAR="/opt/jenkins/jenkins.war"  # 修改为你的 jenkins.war 路径
JENKINS_LOG="/opt/jenkins/jenkins.log"           # 日志文件路径
JENKINS_PID="/opt/jenkins/jenkins.pid"           # PID 文件路径
JENKINS_OPTS="--httpPort=30812"      # 可选: 添加其他启动参数 (如 --httpsPort=8443)

# 检查 Java 是否安装
check_java() {
  if ! command -v java &> /dev/null; then
    echo "错误: 未找到 Java。请先安装 Java 环境。"
    exit 1
  fi
}

# 启动 Jenkins
start() {
  check_java
  if [ -f "$JENKINS_PID" ]; then
    PID=$(cat "$JENKINS_PID")
    if ps -p "$PID" > /dev/null; then
      echo "Jenkins 已在运行 (PID: $PID)"
      exit 0
    else
      rm -f "$JENKINS_PID"
    fi
  fi

  echo "正在启动 Jenkins..."
  nohup java -jar "$JENKINS_WAR" $JENKINS_OPTS > "$JENKINS_LOG" 2>&1 &
  echo $! > "$JENKINS_PID"
  echo "Jenkins 已启动 (PID: $!, 日志: $JENKINS_LOG)"
}

# 停止 Jenkins
stop() {
  if [ -f "$JENKINS_PID" ]; then
    PID=$(cat "$JENKINS_PID")
    if ps -p "$PID" > /dev/null; then
      echo "正在停止 Jenkins (PID: $PID)..."
      kill "$PID"
      rm -f "$JENKINS_PID"
      echo "Jenkins 已停止"
    else
      echo "Jenkins 未运行 (残留 PID 文件)"
      rm -f "$JENKINS_PID"
    fi
  else
    echo "Jenkins 未运行 (未找到 PID 文件)"
  fi
}

# 重启 Jenkins
restart() {
  stop
  sleep 3
  start
}

# 查看状态
status() {
  if [ -f "$JENKINS_PID" ]; then
    PID=$(cat "$JENKINS_PID")
    if ps -p "$PID" > /dev/null; then
      echo "Jenkins 正在运行 (PID: $PID)"
    else
      echo "Jenkins 未运行 (残留 PID 文件)"
    fi
  else
    echo "Jenkins 未运行"
  fi
}

# 主逻辑
case "$1" in
  start)
    start
    ;;
  stop)
    stop
    ;;
  restart)
    restart
    ;;
  status)
    status
    ;;
  *)
    echo "使用方法: $0 {start|stop|restart|status}"
    exit 1
esac

exit 0

