pipeline {
    agent none
    environment {
        IMAGE_NAME = "lpt-prod:${env.GIT_COMMIT?.take(8) ?: '0.0'}"
        CONTAINER_NAME = 'LPT-prod'
        CONTAINER_PORT = '8888'
    }
    stages {
        stage('Build') {
            agent {
                docker {
                    image 'maven:3.9.6-eclipse-temurin-17'
                    args '-v /root/.m2:/root/.m2'
                }
            }
            steps {
                sh 'mvn -B -DskipTests clean package'
            }
        }

        stage('Build Docker Image') {
            agent any  // 使用 Jenkins 默认节点（宿主机），前提是宿主有 docker 命令
            steps {
                sh 'docker build -t $IMAGE_NAME .'
            }
        }

        stage('Run Docker Container') {
            agent any
            steps {
                sh '''
                  docker network create traefik-public || true
                  docker rm -f $CONTAINER_NAME || true
                  docker run -d --name $CONTAINER_NAME \
                  --network traefik-public \
                  --restart=always \
                   -e SPRING_PROFILES_ACTIVE=prod \
                      --label "traefik.enable=true" \
                      --label "traefik.docker.network=traefik-public" \
                      --label 'traefik.http.routers.lpt-api.rule=Host(`lpt.cat-shark.xyz`) && PathPrefix(`/api`)' \
                      --label "traefik.http.routers.lpt-api.entrypoints=websecure" \
                      --label "traefik.http.routers.lpt-api.tls.certresolver=le" \
                      --label "traefik.http.routers.lpt-api.priority=100" \
                      --label "traefik.http.routers.lpt-api.service=lpt-api" \
                      --label "traefik.http.routers.lpt-api.middlewares=lpt-api-strip" \
                      --label "traefik.http.middlewares.lpt-api-strip.stripprefix.prefixes=/api" \
                      --label "traefik.http.services.lpt-api.loadbalancer.server.port=$CONTAINER_PORT" \
                      --log-driver=loki \
                      --log-opt loki-url="http://192.168.123.199:3100/loki/api/v1/push" \
                   $IMAGE_NAME
                  docker network connect mysql-prod_mysql-prod $CONTAINER_NAME || true
                '''
            }
        }

        stage('Check Docker Status') {
            agent any
            steps {
                script {
                    def lastStatus = ''
                    timeout(time: 120, unit: 'SECONDS') {
                        waitUntil {
                            def status = sh(
                                    script: "docker inspect -f '{{.State.Health.Status}}' $CONTAINER_NAME || echo 'unhealthy'",
                                    returnStdout: true
                            ).trim()

                            if (status != lastStatus) {
                                echo "Container health: ${status}"
                                lastStatus = status
                            }
                            return (status == 'healthy')
                        }
                    }
                }
            }
        }

        stage('清理旧镜像') {
            agent any
            steps {
                sh 'docker image prune -af --filter "until=168h" || true'
            }
        }
    }
}
