// IOT 开放网关流水线：拉代码 → 构建 → 部署重启。
// 由 Jenkins 的 iot-open-gateway 任务以「Pipeline script from SCM」读取本文件。
//
// 运行方式：网关 jar 与 Jenkins 在同一台服务器（192.168.114.100）上，直接在本机重启，不走 SSH。
// 敏感配置（GATEWAY_JWT_SECRET / GATEWAY_INTERNAL_SECRET / GATEWAY_ADMIN_SECRET 等）放在服务器上的
// /data/iot/gateway/gateway.env（权限 600），启动前 source 进来，不进仓库。
// 数据库账号密码、后端地址已作为默认值写在 application*.yml 里（内网测试环境）。
pipeline {
    agent any

    tools {
        maven 'Maven-3.8'
        jdk 'JDK17'
    }

    environment {
        DEPLOY_PORT = '18082'
        APP_NAME    = 'iot-open-gateway'
        DEPLOY_DIR  = '/data/iot/gateway'
        // 防止 Jenkins 在任务结束时自动杀掉后台 nohup 进程
        JENKINS_NODE_COOKIE = 'dontKillMe'
        BUILD_ID    = 'dontKillMe'
    }

    stages {
        stage('拉代码') {
            steps {
                git branch: 'main', url: 'https://git.tengwangyun.com/wjh/IoT-OpenApi.git'
            }
        }

        stage('构建') {
            steps {
                // 网关没有单测，跳过测试加快构建
                sh 'mvn -B clean package -DskipTests'
            }
        }

        stage('部署') {
            steps {
                sh '''
                    set -e
                    echo "=== 部署 IOT 开放网关 ==="
                    mkdir -p "${DEPLOY_DIR}"
                    JAR=$(ls target/iot-open-gateway-*.jar | head -1)
                    cp -f "$JAR" "${DEPLOY_DIR}/${APP_NAME}.jar"

                    if [ ! -f "${DEPLOY_DIR}/gateway.env" ]; then
                        echo "缺少 ${DEPLOY_DIR}/gateway.env（存放 GATEWAY_*_SECRET 等），中止" >&2
                        exit 1
                    fi

                    PID=$(lsof -ti:${DEPLOY_PORT} || true)
                    if [ -n "$PID" ]; then
                        echo "停止旧进程 $PID"
                        kill -9 $PID || true
                        sleep 2
                    fi

                    export JENKINS_NODE_COOKIE=dontKillMe
                    export BUILD_ID=dontKillMe
                    set -a
                    . "${DEPLOY_DIR}/gateway.env"
                    set +a
                    nohup java -jar -Dspring.profiles.active=prod "${DEPLOY_DIR}/${APP_NAME}.jar" > "${DEPLOY_DIR}/${APP_NAME}.log" 2>&1 &

                    echo "后台启动中，等待 12 秒检测..."
                    sleep 12
                    lsof -i:${DEPLOY_PORT} || true
                    echo "=== 网关健康检查 ==="
                    curl -sf http://127.0.0.1:${DEPLOY_PORT}/open/gateway/health
                    echo ""
                '''
            }
        }
    }
}
