// 根据选择分支进行构建
pipeline {
    agent any
    environment {
        // 工作空间
        WS = "${WORKSPACE}"
        tagStr = ""
    }

    //定义流水线的加工流程
    stages {

        //流水线的所有阶段
        stage('Environmental inspection') {
            steps {
                println("${BRANCH_NAME}")
                println("${WORKSPACE}")
                sh 'printenv'
                echo "Checking basic information"
                sh 'java -version'
                sh 'git --version'
                sh 'docker version'
                sh 'pwd && ls -alh'
            }
        }
        stage('Get code') {
            steps {
                script{

                    sh 'git config --global http.<https://github.com.proxy> socks5://127.0.0.1:1081'
                    sh 'git config -l'
                    if (DEPLOY_TYPE == "rollback") {
                        // 获取tag,切换tag分支
                        withCredentials([gitUsernamePassword(credentialsId: 'aiyongJenkins', gitToolName: 'Default')]) {
                            script {
                                sh 'git tag -l | xargs git tag -d'
                                // 拉取最新tag
                                sh "git fetch --tags"
                                // 切换tag分支
                                sh "git checkout ${TAG_NAME}"
                            }
                        }
                    } else {
                        echo "不是回滚,不需要获取tag"

                        checkout([$class                           : 'GitSCM', branches: [[name: "${BRANCH_NAME}"]],
                                  doGenerateSubmoduleConfigurations: false, extensions: [[$class: 'CheckoutOption', timeout: 30], [$class: 'CloneOption', depth: 0, noTags: false, reference: '', shallow: false, timeout: 30]], submoduleCfg: [],
                                  userRemoteConfigs                : [[credentialsId: 'aiyongJenkins', url: '<https://github.com/aiyongbao/itr-btit-services-group.git>']]])
                    }
                }
            }
        }

        stage('maven compilation') {
            agent {
                docker {
                    image 'maven:3-alpine'
                    args '-v /var/jenkins_home/appconfig/maven/.m2:/root/.m2 -v /var/jenkins_home/appconfig/maven/settings.xml:/root/.m2/settings.xml'
                }
            }
            steps {
                sh 'pwd && ls -alh'
                sh 'mvn -v'
                sh "echo 默认的工作目录:${WS}"
                sh 'cd ${WS} && mvn clean package -Dmaven.test.skip=true '
            }
        }

        stage('deploy') {
            steps {
                echo "部署..."
                sh 'pwd && ls -alh'
                sh 'cd ${WS}/jeecg-boot-module-system/target && ls'
                sshPublisher(publishers: [sshPublisherDesc(configName: '172.21.0.22', transfers: [sshTransfer(cleanRemote: false, excludes: '', execCommand: '''
                    ID=`ps -ef | grep jeecg-boot-module-system-3.3.0.jar | grep -v grep | awk \\'{print $2}\\'`
                    echo "------start---------"
                    echo "开始执行关闭ID: $ID"
                    echo "关闭进程"
                    # 优雅停机
                    sudo kill -15 $ID
                    #循环120次,每次等待1秒,如果已经关闭则退出,如果最后未关闭强制退出
                    for i in {1..120}
                    do
                                echo "sleep $i"
                                sleep 1
                                ID=`ps -ef | grep jeecg-boot-module-system-2.4.0.jar | grep -v grep | awk \\'{print $2}\\'`
                                
                                # 如果为空,那么表示已经关闭,直接退出循环
                                
                                if [ -n "$PID" ]; then
                                    echo -e ".\\\\c"
                                else
                                    echo "killed"
                                    break
                                fi
                    done
                    #如果正常关闭失败,那么进行强制 kill -9 进行关闭
                    if [ -n "$PID" ]; then
                                echo "kill -9 $ID"
                                sudo kill -9 $ID
                    else
                    # 正常关闭,提示输出
                                echo "服务正常关闭...."
                    fi
                    BUILD_ID=dontKillMe
                    cd /home/aiyong/digital_java/target
                    sudo nohup  java -server -Xmx2G -Xms2G -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/home/aiyong/digital_java/target/heapError -jar  -Dspring.profiles.active=prod   jeecg-boot-module-system-3.3.0.jar > ./output.log 2>&1 &
                    sleep 1
                    cp jeecg-boot-module-system-3.3.0.jar ..
                    echo "------end---------"
                ''', execTimeout: 120000, flatten: false, makeEmptyDirs: false, noDefaultExcludes: false, patternSeparator: '[, ]+', remoteDirectory: '/home/aiyong/digital_java', remoteDirectorySDF: false, removePrefix: 'jeecg-boot-module-system', sourceFiles: 'jeecg-boot-module-system/target/jeecg-boot-module-system-3.3.0.jar')], usePromotionTimestamp: false, useWorkspaceInPromotion: false, verbose: true)])
            }
        }

        stage('git build tag') {
            steps {
                // 判断
                script {

                    if (env.DEPLOY_TYPE == 'rollback') {
                        echo "回滚,不需要打tag"
                    } else {
                        echo "打tag"
                        withCredentials([gitUsernamePassword(credentialsId: 'aiyongJenkins', gitToolName: 'Default')]) {

                            // 删除本地所有tag
                            sh 'git tag -l | xargs git tag -d'
                            // 拉取最新tag
                            sh 'git fetch --tags'

                            def GIT_AUTHOR_NAME = 'aiyongJenkins'
                            def GIT_AUTHOR_EMAIL = 'aiyongJenkins@mail.com'
                            // 设置git邮箱
                            sh "git config --global user.email ${GIT_AUTHOR_NAME}"
                            // 设置git用户名
                            sh "git config --global user.name ${GIT_AUTHOR_EMAIL}"

                            try {
                                def recentlyTag = ""
                                // 获取远程所有tag,按照时间排序
                                def tagSortListByCreateTime = sh(script: 'git tag -l --sort=-creatordate', returnStdout: true).trim().tokenize('\\n')
                                // 循环tags,获取以v前缀开头的tag
                                for (int i = 0; i < tagSortListByCreateTime.size(); i++) {
                                    echo "tag: ${tagSortListByCreateTime[i]}"
                                    if (tagSortListByCreateTime[i].startsWith('digital.v')) {
                                        recentlyTag = tagSortListByCreateTime[i].replace('digital.v', '')
                                        break
                                    }
                                }
                                echo "recentlyTag: ${recentlyTag}"

                                // 如果recentlyTag为空,说明没有以v开头的tag,那么就从1开始
                                if (recentlyTag == "") {
                                    recentlyTag = "1.0.0";
                                }
                                // 获取最新tag
                                def recentlyTagArr = recentlyTag.split("\\\\.")
                                // 获取最新tag的最后一位
                                def recentlyTagLast = recentlyTagArr[recentlyTagArr.size() - 1]
                                // 最新tag的最后一位+1
                                def recentlyTagLastAdd = recentlyTagLast.toInteger() + 1
                                // 替换最新tag的最后一位
                                recentlyTagArr[recentlyTagArr.size() - 1] = recentlyTagLastAdd
                                // 拼接tag
                                tagStr = "digital.v" + recentlyTagArr.join(".")

                            }catch (Exception e){
                                echo "获取最新tag失败,使用默认tag${e.getMessage()}"
                                // 如果tags为空,初始化版本
                                tagStr = "digital.v1.0.0";
                            }
                            println "tagStr: ${tagStr}"

                        }
                    }
                }

            }
        }
    }

    // post必走
    post {
        always {
            script {
                echo "构建结果:always"
                // 如果是tag拉出来的分支,回倒是scm获取不到分支和tag列表
                if (DEPLOY_TYPE == 'rollback') {
                    // 切换主分支
                    checkout([$class                           : 'GitSCM', branches: [[name: "main"]],
                              doGenerateSubmoduleConfigurations: false, extensions: [[$class: 'CheckoutOption', timeout: 30], [$class: 'CloneOption', depth: 0, noTags: false, reference: '', shallow: false, timeout: 30]], submoduleCfg: [],
                              userRemoteConfigs                : [[credentialsId: 'aiyongJenkins', url: '<https://github.com/aiyongbao/itr-btit-services-group.git>']]])
                }
            }
        }

        success {
            script {
                echo "构建结果:success"
                if(DEPLOY_TYPE == 'deploy'){
                    withCredentials([gitUsernamePassword(credentialsId: 'aiyongJenkins', gitToolName: 'Default')]) {
                        def currentDate = new Date().format("yyyyMMddHHmmss");
                        // 打tag
                        sh "git tag -a ${tagStr} -m 'tag ${tagStr}-${currentDate}'"
                        // 推送tag
                        sh "git push origin ${tagStr}"
                    }
                }
            }
        }

        failure {
            script {
                echo "构建结果:failure"
                if(DEPLOY_TYPE == "deploy"){
                    echo "部署失败"
                }
            }
        }
    }
}