@Library("p8-jenkins-utils@1.49")

def name = "ftp-poller"
def image = 'integration-demo-' + name
def repo = 'https://gitea.predic8.de/P8-Demo/integration-microservices-ftp-poller-deploy.git'


final def p8 = new de.predic8.jenkinsutils.P8(this, scm, image)

pipeline {
    agent {
        kubernetes {
            yamlFile 'ci-cd/predic8-cluster/KubernetesBuildPod.yaml'
        }
    }

    stages {

        stage('Git Checkout') {
            steps {
                script {
                    p8.git.checkTriggerCheckoutAndCheckTag()
                }
            }
        }

        stage('Build Buildah Image') {
            steps {
                container('buildah') {
                    script {
                        p8.oci.repoLogin()
                        p8.oci.buildV2('ci-cd/predic8-cluster/')
                    }
                }
            }
        }

        stage('Push Buildah Image') {
            steps {
                container('buildah') {
                    script {
                        p8.oci.pushV2()
                    }
                }
            }
        }

        stage('Deploy') {
            steps {
                dir('tmp') {
                    script {

                        p8.git.checkout url: repo

                        // container('kubectl') {
                        //     p8.kubectl.patchKubernetesDeploymentFile(containerName: name, filePath:'auto/', fileName:'deploy.yaml')
                        // }

                        container('kubectl') {

                            echo "Build number is ${currentBuild.number}"
                            sh "cat auto/patch.yml"
                            sh "sed 's/\$VERSION/${currentBuild.number}/g' auto/patch.yml > auto/patch-temp.yml"
                            echo "Nach sed:"
                            sh "cat auto/patch-temp.yml"

                            echo "Build Nr: ${currentBuild.number}"
                            sh "kubectl patch -f auto/deploy.yaml  --local --patch-file auto/patch-temp.yml -o yaml > temp.yaml"
                            sh "mv temp.yaml auto/deploy.yaml"
                            sh "cat auto/deploy.yaml"
                        }

                        p8.git.addCommitTagAndPush(url: repo)

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

    post {
        always {
            cleanWs()
        }
    }
}
