#!/usr/bin/env groovy
library 'status-jenkins-lib@v1.8.18'

pipeline {
  agent { label 'linux' }

  parameters {
    string(
      name: 'BRANCH',
      defaultValue: 'develop',
      description: 'Name of branch to build.'
    )
    booleanParam(
      name: 'RELEASE',
      defaultValue: false,
      description: 'Enable to create build for release.',
    )
    string(
      name: 'RELEASE_IMAGE_TAG',
      description: 'Release Docker image tag.',
      defaultValue: params.RELEASE_IMAGE_TAG ?: 'deploy-test',
    )
  }

  options {
    timestamps()
    /* Prevent Jenkins jobs from running forever */
    timeout(time: 10, unit: 'MINUTES')
    disableConcurrentBuilds()
    /* Go requires a certain directory structure */
    checkoutToSubdirectory('src/github.com/status-im/status-go')
    /* manage how many builds we keep */
    buildDiscarder(logRotator(
      numToKeepStr: '5',
      daysToKeepStr: '30',
      artifactNumToKeepStr: '1',
    ))
  }

  environment {
    PLATFORM = "docker"
    REPO     = "${env.WORKSPACE}/src/github.com/status-im/status-go"
    GOPATH   = "${env.WORKSPACE}"
    GOCACHE  = "${WORKSPACE_TMP}/gocache"
    PATH     = "/usr/local/go/bin:${env.PATH}:${env.GOPATH}/bin"
    /* Makefile parameters */
    DOCKER_IMAGE_NAME = 'statusteam/status-go'
    DOCKER_IMAGE_CUSTOM_TAG = "ci-build-${git.commit()}"
  }

  stages {
    stage('Prep') { steps { dir(env.REPO) { script {
      println("Output: ${env.DOCKER_IMAGE_NAME}:${env.RELEASE_IMAGE_TAG}")
    } } } }

    stage('Build') { steps { dir(env.REPO) { script {
      sh 'make docker-image'
      image = docker.image("${env.DOCKER_IMAGE_NAME}:${env.DOCKER_IMAGE_CUSTOM_TAG}")
    } } } }

    stage('Push') { steps { dir(env.REPO) { script {
      withDockerRegistry([credentialsId: "dockerhub-statusteam-auto", url: ""]) {
        image.push("v${utils.getVersion()}-${git.commit()}")
      }
    } } } }

    stage('Deploy') {
      when { expression { params.RELEASE == true } }
      steps { dir(env.REPO) { script {
        withDockerRegistry([credentialsId: "dockerhub-statusteam-auto", url: ""]) {
          image.push(env.RELEASE_IMAGE_TAG)
        }
    } } } }
  } // stages
  post {
    success { script { github.notifyPR(true) } }
    failure { script { github.notifyPR(false) } }
    always  { dir(env.REPO) {
      sh 'make clean-docker-images'
    } }
  } // post
} // pipeline