pipeline {
    agent {
        docker {
            image "cicd/ubuntu:22.04-docker-py312-jdk8-nodejs20-mvn389"
            args '-v /var/run/docker.sock:/var/run/docker.sock -v /home/jenkins:/home/jenkins -v /etc/docker:/etc/docker'
            registryUrl 'https://39.170.26.156:8443'
            registryCredentialsId '3a4a4463-784d-4e91-9457-9dfd64722ecb'
        }
    }

    environment {
        GIT_URL = 'https://wdxz-gitea.best-envision.com/qiaoxinjiu/effekt-interface.git'
        GIT_BRANCH = 'master'

        REPO_HOST = '39.170.26.156:8443'
        REGISTRY = '39.170.26.156:8443'
        HARBOR_PROJECT = 'effekt'
        IMAGE_REPO = 'effekt-interface'
        IMAGE_NAME = "${REGISTRY}/${HARBOR_PROJECT}/${IMAGE_REPO}"
        BUILD_IMAGE = '39.170.26.156:8443/cicd/ubuntu:22.04-docker-py312-jdk8-nodejs20-mvn389'

        DEPLOY_HOST = '124.220.32.45'
        DEPLOY_PORT = '22'
        DEPLOY_USER = 'user'
        CONTAINER_NAME = 'effekt-interface'
        HOST_PORT = '5010'
        CONTAINER_PORT = '5010'
    }

    options {
        timestamps()
        disableConcurrentBuilds()
        buildDiscarder(logRotator(numToKeepStr: '20'))
    }

    stages {
        stage('Checkout Code') {
            steps {
                git branch: "${GIT_BRANCH}",
                    credentialsId: 'ebe42f70-146f-4a4b-8090-eded24a77173',
                    url: "${GIT_URL}"
            }
        }

        stage('Check Environment') {
            steps {
                sh '''
                    set -e
                    echo "=== Build Container Environment ==="
                    whoami
                    docker --version
                    git --version
                    command -v python >/dev/null 2>&1 && python --version || echo "python: not installed"
                    command -v python3 >/dev/null 2>&1 && python3 --version || echo "python3: not installed"
                    command -v pip >/dev/null 2>&1 && pip --version || echo "pip: not installed"
                    command -v pip3 >/dev/null 2>&1 && pip3 --version || echo "pip3: not installed"
                    echo "=== Workspace ==="
                    pwd
                    ls -la
                '''
            }
        }

        stage('Build Docker Image') {
            steps {
                withDockerRegistry(registry: [credentialsId: '3a4a4463-784d-4e91-9457-9dfd64722ecb', url: 'https://39.170.26.156:8443']) {
                    sh '''
                        set -e
                        export DOCKER_BUILDKIT=0
                        docker pull 39.170.26.156:8443/library/python:3.10-bookworm
                        docker build --no-cache \
                          -t ${IMAGE_NAME}:${BUILD_NUMBER} \
                          -t ${IMAGE_NAME}:latest \
                          -f Dockerfile \
                          .
                    '''
                }
            }
        }

        stage('Push Image To Harbor') {
            steps {
                withDockerRegistry(registry: [credentialsId: '3a4a4463-784d-4e91-9457-9dfd64722ecb', url: 'https://39.170.26.156:8443']) {
                    sh '''
                        set -e
                        docker push ${IMAGE_NAME}:${BUILD_NUMBER}
                        docker push ${IMAGE_NAME}:latest
                    '''
                }
            }
        }

        stage('Deploy To Server') {
            steps {
                script {
                    deploy_node_by_password(
                        remote_host: env.DEPLOY_HOST,
                        remote_port: env.DEPLOY_PORT,
                        credentials_id: '82d14a67-250f-46b0-8b13-50e874a11933'
                    )
                }
            }
        }

        stage('Verify') {
            steps {
                script {
                    withCredentials([
                        usernamePassword(
                            credentialsId: '82d14a67-250f-46b0-8b13-50e874a11933',
                            passwordVariable: 'DEPLOY_PASS',
                            usernameVariable: 'DEPLOY_USER_CREDENTIAL'
                        )
                    ]) {
                        def remote = [:]
                        remote.name = env.DEPLOY_HOST
                        remote.host = env.DEPLOY_HOST
                        remote.port = Integer.valueOf(env.DEPLOY_PORT)
                        remote.allowAnyHosts = true
                        remote.user = DEPLOY_USER_CREDENTIAL
                        remote.password = DEPLOY_PASS

                        sshCommand remote: remote, sudo: false, command: """
                            set -e
                            sleep 10
                            docker ps -a --filter name=${CONTAINER_NAME}
                            docker inspect ${CONTAINER_NAME} --format '{{.State.Status}}'
                            docker logs --tail 100 ${CONTAINER_NAME} || true
                            curl -v http://127.0.0.1:${HOST_PORT}
                        """
                    }
                }
            }
        }
    }

    post {
        success {
            echo '流水线执行成功：代码拉取、构建、推送、部署已完成'
        }
        failure {
            echo '流水线执行失败：请查看对应阶段日志'
        }
        always {
            sh '''
                docker image prune -f || true
            '''
        }
    }
}

def deploy_node_by_password(Map args) {
    withCredentials([
        usernamePassword(
            credentialsId: args.credentials_id,
            passwordVariable: 'DEPLOY_PASS',
            usernameVariable: 'DEPLOY_USER_CREDENTIAL'
        ),
        usernamePassword(
            credentialsId: '3a4a4463-784d-4e91-9457-9dfd64722ecb',
            passwordVariable: 'HARBOR_PASS',
            usernameVariable: 'HARBOR_USER'
        )
    ]) {
        def remote = [:]
        remote.name = args.remote_host
        remote.host = args.remote_host
        remote.port = Integer.valueOf(args.remote_port)
        remote.allowAnyHosts = true
        remote.user = DEPLOY_USER_CREDENTIAL
        remote.password = DEPLOY_PASS

        def deployCommand = """
            set -e
            echo '${HARBOR_PASS}' | docker login '${REGISTRY}' -u '${HARBOR_USER}' --password-stdin
            docker pull '${IMAGE_NAME}:latest'
            docker rm -f '${CONTAINER_NAME}' || true
            docker run -d \
              --name '${CONTAINER_NAME}' \
              --restart always \
              --network host \
              '${IMAGE_NAME}:latest'
            docker logout '${REGISTRY}' || true
        """

        sshCommand remote: remote, sudo: false, command: deployCommand
    }
}
