@Library('cloudbees-pipeline-libs') _

def dockerLabel = getDockerLabel()

pipeline {
  agent {
    kubernetes {
      label 'honeyui-build-' + UUID.randomUUID().toString()
      yamlFile 'conf/pods.yaml'
    }
  }

  options {
      timeout(time: 30, unit: 'MINUTES')
  }

  stages {
    stage('Build') {
      steps{
        parallel(
          app: {
            container(name: "kaniko", shell: '/busybox/sh') {
              buildImage("./Dockerfile", [ "honeyui/honeyui-react-docs:${dockerLabel}", "honeyui/honeyui-react-docs:latest" ], dockerLabel)
            }
          }
        )
      }
    }

    stage("Deploy") {
        when {
          anyOf {
            branch 'master';
          }
        }
        steps {
          script {
            build job: "../deploy-staging",
              parameters: [
                string(name: 'DOCKER_LABEL', value: dockerLabel),
                string(name: 'GCP_ENVIRONMENT', value: "staging")
              ]
          }
        }
    }
  }
}

def buildImage(dockerFile, images, imageLabel) {
  withCredentials([
    file(credentialsId: 'g3-honeyui-gcr-w', variable: 'kanikosecret')
    ]) {
    withEnv(['PATH+EXTRA=/busybox:/kaniko', "GOOGLE_APPLICATION_CREDENTIALS=${kanikosecret}"]) {
      def script = """#!/busybox/sh
        # Use for debugging: -v debug
        /kaniko/executor \\
          --single-snapshot \\
          -f ${dockerFile} \\
          --cache=true \\
          -c `pwd` \\
        """
      images.each { image ->
        script += "--destination gcr.io/cloudbees-ops-gcr/${image} \\\n"
      }

      script += "--cache=true\n"

      sh script
      currentBuild.description = imageLabel
    }
  }
}

def getDockerLabel() {
  def branch = env.BRANCH_NAME.toLowerCase().replaceAll(/[^a-z0-9]/, "-")
  return "build-${branch}-${env.BUILD_ID}"
}
