pipeline {
  agent {
    kubernetes {
      label "kaniko-${UUID.randomUUID().toString()}"
      inheritFrom 'kaniko'
    }
  }
  environment {
        REPOSITORY = 'yardstick/measure-solver'
  }
  stages {
      stage('Build Kaniko image') {
        steps {
          withCredentials([usernamePassword(credentialsId: 'DockerHubAccessYardstick', usernameVariable: 'USER', passwordVariable: 'PASS')]) {
            container('kaniko') {
                checkout scm
                // Setup docker credentials
                sh 'echo "{\\"auths\\":{\\"https://index.docker.io/v1/\\":{\\"auth\\":\\"$(printf "%s:%s" "$USER" "$PASS" | base64 | tr -d \'\n\')\\"}}}" > /kaniko/.docker/config.json'
                // Execute kaniko build
                sh """
                    /kaniko/executor -f `pwd`/Dockerfile \
                        -c `pwd` \
                        --insecure=true \
                        --insecure-registry=docker-registry.default:5000 \
                        --cache=true \
                        --cache-repo=docker-registry.default:5000/${REPOSITORY} \
                        --destination ${env.REPOSITORY}:\$(echo ${BRANCH_NAME} | grep -Eo 'feature/([A-Za-z]+-[0-9]*)' | grep -Eo '[A-Za-z]+-[0-9]*' || \
                            echo ${BRANCH_NAME} | grep -Eo '(release|hotfix)/[[:digit:]]+\\.[[:digit:]]+\\.[[:digit:]]+' | grep -Eo '[[:digit:]]+\\.[[:digit:]]+\\.[[:digit:]]+' || \
                            echo ${BRANCH_NAME} | grep -Eo 'YASDEV-([[:digit:]]*)')
                """
          }
        }
      }
    }
  }
}