#!/usr/bin/env groovy

@Library('apm@current') _

pipeline {
  agent { label 'linux && immutable' }
  environment {
    REPO = 'ecs-logging-go-zap'
    BASE_DIR = "src/go.elastic.co/apm/${env.REPO}"
    NOTIFY_TO = credentials('notify-to')
    JOB_GCS_BUCKET = credentials('gcs-bucket')
    HOME = "${env.WORKSPACE}"
    PATH = "${env.HOME}/bin:${env.PATH}"
    GO111MODULE = 'on'
    GO_VERSION = '1.13.9'
    GOPATH = "${env.WORKSPACE}"
  }
  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}", githubNotifyFirstTimeContributor: true)
        stash allowEmpty: true, name: 'source', useDefaultExcludes: false
      }
    }
    stage('Sanity checks') {
      options { skipDefaultCheckout() }
      steps {
        deleteDir()
        unstash 'source'
        dir("${BASE_DIR}"){
          preCommit(commit: "${GIT_BASE_COMMIT}", junit: true)
        }
      }
    }
    stage('Test') {
      options { skipDefaultCheckout() }
      steps {
        withGithubNotify(context: 'Test', tab: 'tests') {
          deleteDir()
          unstash 'source'
          dir("${BASE_DIR}"){
            sh script: '.ci/scripts/run-tests.sh', label: 'Run tests'
          }
        }
      }
      post {
        always {
          junit(allowEmptyResults: true, keepLongStdio: true, testResults: "${BASE_DIR}/**/junit-*.xml")
        }
      }
    }
  }
  post {
    cleanup {
      notifyBuildResult()
    }
  }
}
