pipeline {
  agent {
    kubernetes {
      cloud 'kubernetes-ACK'
      slaveConnectTimeout 1200
      workspaceVolume hostPathWorkspaceVolume(hostPath: "/mnt/workspace", readOnly: false)
      yaml '''
apiVersion: v1
kind: Pod
spec:
  containers:
    - args: [\'$(JENKINS_SECRET)\', \'$(JENKINS_NAME)\']
      image: 'harbor.51trust.net/zyyl/jnlp-slave:latest'
      #image: 'jenkinsci/jnlp-slave:3.36-2'
      name: jnlp
      imagePullPolicy: IfNotPresent
      volumeMounts:
        - mountPath: "/etc/localtime"
          name: "localtime"
          readOnly: false
    - command:
        - "cat"
      env:
        - name: "LANGUAGE"
          value: "en_US:en"
        - name: "LC_ALL"
          value: "en_US.UTF-8"
        - name: "LANG"
          value: "en_US.UTF-8"
      image: "harbor.51trust.net/zyyl/node:16.20.0-bullseye"
      imagePullPolicy: "IfNotPresent"
      name: "build"
      tty: true
      volumeMounts:
        - mountPath: "/etc/localtime"
          name: "localtime"
        - mountPath: "/root/.m2/"
          name: "cachedir"
          readOnly: false
    - command:
        - "cat"
      env:
        - name: "LANGUAGE"
          value: "en_US:en"
        - name: "LC_ALL"
          value: "en_US.UTF-8"
        - name: "LANG"
          value: "en_US.UTF-8"
      image: "registry.cn-beijing.aliyuncs.com/citools/kubectl:self-1.17"
      imagePullPolicy: "IfNotPresent"
      name: "kubectl"
      tty: true
      volumeMounts:
        - mountPath: "/etc/localtime"
          name: "localtime"
          readOnly: false
#配置kaniko slave pod镜像
    - command:
      - /bin/sh
      - -c
      args: 
        - cat 
      tty: true
      volumeMounts:
        - name: kaniko-secret
          mountPath: /kaniko/.docker
      env:
        - name: "LANGUAGE"
          value: "en_US:en"
        - name: "LC_ALL"
          value: "en_US.UTF-8"
        - name: "LANG"
          value: "en_US.UTF-8"
      image: registry.cn-beijing.aliyuncs.com/devops-tols/kaniko-executor:debug
      imagePullPolicy: Always
      name: "kaniko"
      tty: true
  nodeSelector:
    jenkins-build: "true"
  volumes:
    - name: kaniko-secret
      secret:
        secretName: kaniko-secret
        items:
          - key: config.json
            path: config.json
    - hostPath:
        path: "/usr/share/zoneinfo/Asia/Shanghai"
      name: "localtime"
    - name: "cachedir"
      hostPath:
        path: "/opt/m2"
'''
    }
}
  stages {
    stage('Pulling Code') {
      parallel {
        stage('Pulling Code by Jenkins') {
          when {
            expression {
              env.gitlabBranch == null
            }

          }
          steps {
            git(changelog: true, poll: true, url: 'https://gitea.51trust.net/front/acupuncture-moxibustion-admin.git', branch: "${BRANCH}", credentialsId: 'GITEA_ACCOUNT')
            script {
              COMMIT_ID = sh(returnStdout: true, script: "git log -n 1 --pretty=format:'%h'").trim()
              TAG = BUILD_TAG + '-' + COMMIT_ID
              println "Current branch is ${BRANCH}, Commit ID is ${COMMIT_ID}, Image TAG is ${TAG}"

            }

          }
        }

        stage('Pulling Code by trigger') {
          when {
            expression {
              env.gitlabBranch != null
            }

          }
          steps {
            git(url: 'https://gitea.51trust.net/front/acupuncture-moxibustion-admin.git', branch: env.gitlabBranch, changelog: true, poll: true, credentialsId: 'GITEA_ACCOUNT')
            script {
              COMMIT_ID = sh(returnStdout: true, script: "git log -n 1 --pretty=format:'%h'").trim()
              TAG = BUILD_TAG + '-' + COMMIT_ID
              println "Current branch is ${env.gitlabBranch}, Commit ID is ${COMMIT_ID}, Image TAG is ${TAG}"
            }

          }
        }

      }
    }

    stage('Building') {
      steps {
        container(name: 'build') {
            sh """
            node -v 
            npm install --registry=https://registry.npmmirror.com;npm run build:pro
            #yarn install --registry=https://registry.npmmirror.com/;yarn build:pro
            ls dist/*
            """
        }
      }
    }

    stage('Docker build for creating image') {
      environment {
        HARBOR_USER = credentials('HARBOR_ACCOUNT')
    }
      steps {
        container(name: 'kaniko') {
          sh """
          echo ${HARBOR_USER_USR} ${HARBOR_USER_PSW} ${TAG}
          pwd
          ls *
          mkdir -p repo/${IMAGE_NAME}
          cp -r dist/ repo/${IMAGE_NAME}
          cp  envconfig/Dockerfile  repo/${IMAGE_NAME}
          cp  envconfig/nginx.conf repo/${IMAGE_NAME}
          cd repo/${IMAGE_NAME}
          ls *
          /kaniko/executor -f Dockerfile -c ./ -d ${HARBOR_ADDRESS}/${REGISTRY_DIR}/${IMAGE_NAME}:${TAG} --force
          """
        }
      }
    }

    stage('Deploying to K8s') {
      environment {
        MY_KUBECONFIG = credentials('k8s-kubeconfig')
    }
      steps {
        wrap([$class: 'BuildUser']) {
           script {
                BUILD_USER = "${env.BUILD_USER}"
                BUILD_USER_ID ="${BUILD_USER_ID}"
                    }
          }
          script {
                env.BUILD_USERNAME = "${BUILD_USER}"
                env.BUILD_USERNAMEID = "${BUILD_USER_ID}"
                       }
        container(name: 'kubectl'){
           sh """
           /usr/local/bin/kubectl --kubeconfig $MY_KUBECONFIG set image deploy -l app=${IMAGE_NAME} ${IMAGE_NAME}=${HARBOR_ADDRESS}/${REGISTRY_DIR}/${IMAGE_NAME}:${TAG} -n $NAMESPACE
           """
        }
      }
    }

  }
  environment {
    COMMIT_ID = ""
    HARBOR_ADDRESS = "harbor.51trust.net"
    REGISTRY_DIR = "gfzj"
    IMAGE_NAME = "front-acup"
    NAMESPACE = "gfzj"
    TAG = ""
  }
  parameters {
    gitParameter(branch: '', branchFilter: 'origin/(.*)', defaultValue: '', description: 'Branch for build and deploy', name: 'BRANCH', quickFilterEnabled: false, selectedValue: 'NONE', sortMode: 'NONE', tagFilter: '*', type: 'PT_BRANCH')
  }
}
