def normalizedBranchName = "${BRANCH_NAME}".replaceAll('/','-').replaceAll('%2F','-').replaceAll('_','-').toLowerCase()
def imageTag = "${normalizedBranchName}-${env.BUILD_ID}"
def imageBuildId = "${env.BUILD_ID}"
def dockerDeployWriteRegistry = "https://index.docker.io/v1/"
def project = "abitypo3cms"
def gitRepoEmail = "k.sieren@meramo.de"
def imageNameWithTag = "kerstinsieren/abitypo3cms:${imageTag}"
def imageNameTagLatest = "kerstinsieren/abitypo3cms:${normalizedBranchName}-latest"
def helmGitRepo = "git2.meramo.org/helm_charts/abi-typo3-chart.git"


pipeline {
    agent {
      kubernetes  {
            label 'jenkins-slave'
             defaultContainer 'jnlp'
      yaml """
apiVersion: v1
kind: Pod
spec:
  containers:
  - name: docker
    image: docker:1.11
    command:
    - cat
    tty: true
    volumeMounts:
        - name: dockersock
          mountPath: /var/run/docker.sock
  - name: tools
    image: argoproj/argo-cd-ci-builder:v1.0.0
    command:
    - cat
    tty: true
  volumes:
    - name: dockersock
      hostPath:
        path: /var/run/docker.sock
"""
        }
    }
  environment {
      IMAGE_REPO = "${imageNameWithTag}"
  }
  stages {
    stage('Build') {
      environment {
        DOCKERHUB_CREDS = credentials('deploy-docker-id')
      }
      steps {
        container('docker') {
          sh "echo ${env.GIT_COMMIT}"
          sh "docker build --no-cache -t ${imageNameWithTag} . && docker tag ${imageNameWithTag} ${imageNameTagLatest}"
          sh "docker login --username $DOCKERHUB_CREDS_USR --password $DOCKERHUB_CREDS_PSW && docker push ${imageNameWithTag} && docker push ${imageNameTagLatest}"
          sh "docker run --rm --entrypoint tar ${imageNameWithTag} cCj /var/www . > ${project}-${imageTag}.tar.bz2"
          archiveArtifacts "${project}-${imageTag}.tar.bz2"
          stash "${project}-${imageTag}.tar.bz2"
          sh "rm ${project}-${imageTag}.tar.bz2"
        }
      }
    }
    stage('Update Helm Chart') {
      environment {
        GIT_CREDS = credentials('deploy-git-id')
        HELM_GIT_REPO_URL = "${helmGitRepo}"
        GIT_REPO_EMAIL = "${gitRepoEmail}"
        GIT_REPO_BRANCH = "${normalizedBranchName}"
      }
      steps {
        container('tools') {
            sh "git clone https://${env.HELM_GIT_REPO_URL}"
            sh "git config --global user.email ${env.GIT_REPO_EMAIL}"
            sh "git config --global user.name ${env.GIT_CREDS_USR}"
            sh "wget https://github.com/mikefarah/yq/releases/download/v4.9.6/yq_linux_amd64.tar.gz"
            sh "tar xvf yq_linux_amd64.tar.gz"
            sh "mv yq_linux_amd64 /usr/bin/yq"
          dir("abi-typo3-chart") {
          withCredentials([gitUsernamePassword(credentialsId: 'deploy-git-id', gitToolName: 'git-tool')]) {
              sh "git checkout ${normalizedBranchName}"
              sh '''#!/bin/bash
              echo $GIT_REPO_EMAIL
              echo $GIT_COMMIT
              ls -lth
              yq eval '.image.repository = env(IMAGE_REPO)' -i values.yaml
              yq eval '.image.tag = env(GIT_COMMIT)' -i values.yaml
              cat values.yaml
              '''
              sh "git add values.yaml"
              sh "git commit -m \"Triggered Build '$GIT_COMMIT'\""
              sh "git push https://$HELM_GIT_REPO_URL"
            }
          }
        }
      }
    }
  }
}
