#!/usr/bin/env groovy

@Library('apm@current') _

pipeline {
  agent { label 'ubuntu && immutable' }
  environment {
    BASE_DIR="src/github.com/elastic/elastic-agent-client"
    PIPELINE_LOG_LEVEL='INFO'
    GO_VERSION = '1.13.12'
  }
  options {
    timeout(time: 1, unit: 'HOURS')
    buildDiscarder(logRotator(numToKeepStr: '20', artifactNumToKeepStr: '20', daysToKeepStr: '30'))
    timestamps()
    ansiColor('xterm')
    disableResume()
    durabilityHint('PERFORMANCE_OPTIMIZED')
    rateLimitBuilds(throttle: [count: 60, durationName: 'hour', userBoost: true])
    quietPeriod(10)
  }
  triggers {
    issueCommentTrigger('(?i).*(?:jenkins\\W+)?run\\W+(?:the\\W+)?tests(?:\\W+please)?.*')
  }
  stages {
    stage('Checkout') {
      options { skipDefaultCheckout() }
      steps {
        pipelineManager([ cancelPreviousRunningBuilds: [ when: 'PR' ] ])
        deleteDir()
        gitCheckout(basedir: "${BASE_DIR}")
        stash allowEmpty: true, name: 'source', useDefaultExcludes: false
      }
    }
    stage('Lint') {
      options { skipDefaultCheckout() }
      steps {
        cleanup()
        withMageEnv(){
          dir("${BASE_DIR}"){
            sh(label: 'Checks formatting / linting',script: 'mage -debug check:all')
          }
        }
      }
    }
    stage('Update') {
      options { skipDefaultCheckout() }
      steps {
        cleanup()
        withMageEnv(pkgs: [
          "golang.org/x/lint/golint",
          "github.com/golang/protobuf/proto",
          "github.com/golang/protobuf/protoc-gen-go",
          ]){
          sh '''
          curl -sSfL -o protoc.zip https://github.com/protocolbuffers/protobuf/releases/download/v3.12.3/protoc-3.12.3-linux-x86_64.zip
          unzip protoc.zip
          '''
          dir("${BASE_DIR}"){
            sh(label: 'Checks formatting / linting',script: 'mage -debug update')
          }
        }
      }
    }
    stage('Test') {
      options { skipDefaultCheckout() }
      steps {
        cleanup()
        withMageEnv(){
          dir("${BASE_DIR}"){
            sh(label: 'Unit test', script: 'go test -race ./...|tee tests-report.txt')
          }
        }
      }
      post {
        always {
          convertGoTestResults(
            input: "${BASE_DIR}/tests-report.txt",
            output: "${BASE_DIR}/junit-report.xml"
          )
        }
      }
    }
  }
  post {
    cleanup {
      notifyBuildResult(prComment: true)
    }
  }
}

def cleanup(){
  dir("${BASE_DIR}"){
    deleteDir()
  }
  unstash 'source'
}
