@Library("p8-jenkins-utils@1.47") _

def p8 = new de.predic8.jenkinsutils.P8(this, scm, "integration-demo-artemis")

// Automatisch mit Push bauen!
// properties([
//     pipelineTriggers([[$class:"SCMTrigger", scmpoll_spec:""]]),
// ])

podTemplate(
  containers: [
     containerTemplate(name: 'buildah', image: 'hub.predic8.de/p8/buildah:259', ttyEnabled: true, command: 'cat'),
     containerTemplate(name: 'kubectl', image: 'hub.predic8.de/p8/kubectl:8', ttyEnabled: true, command: 'cat'),
     containerTemplate(name: 'argocd-client', image: 'hub.predic8.de/p8/argocd-client:4', ttyEnabled: true, command: 'cat'),
  ],
  imagePullSecrets: ['p8-hub-credentials']) {

    node(POD_LABEL) {
        stage('Checkout') {
            p8.git.checkTriggerCheckoutAndCheckTag()
        }

        container('buildah') {
            stage('Build') {
    			p8.oci.repoLogin()
                //p8.maven.useInternalRepo()
                p8.oci.buildV2('/',false)
            }
            stage('Push') {
                p8.oci.pushV2()
            }
        }

         stage('Tag') {
            p8.git.tagAndPush()
        }

        stage('Deploy') {
            dir('deploy') {
                git credentialsId: "350ecaca-7d1f-4acf-9602-8791a4a866b6", url: "https://gitea.predic8.de/P8-Demo/integration-microservices-artemis-deploy.git"

                container('kubectl') {
    			    p8.kubectl.patchKubernetesDeploymentFile('integration-demo-artemis', 'auto/', 'deploy.yaml')
                    sh 'cat auto/deploy.yaml'
                }

                withCredentials([usernamePassword(credentialsId: "350ecaca-7d1f-4acf-9602-8791a4a866b6", usernameVariable: 'GIT_USERNAME', passwordVariable: 'GIT_PASSWORD')]) {
                    sh """
                    git config --global user.name Jenkins
                    git config --global user.email jenkins@predic8.de
                    git add .
                    git commit -m "deploy version $BUILD_NUMBER"
                    git push https://${GIT_USERNAME}:${GIT_PASSWORD}@gitea.predic8.de/P8-Demo/integration-microservices-artemis-deploy.git"""
                }
            }

            container('argocd-client') {
                p8.argo.syncAndWait('artemis')
            }
        }       
    }
}