#!/usr/bin/env groovy

@Library('apm@current') _

pipeline {
  agent { label 'ubuntu-20.04 && immutable' }
  environment {
    REPO = "elastic-agent-system-metrics"
    BASE_DIR = "src/github.com/elastic/${env.REPO}"
    JOB_GIT_CREDENTIALS = "f6c7695a-671e-4f4f-a331-acdce44ff9ba"
    PIPELINE_LOG_LEVEL = 'INFO'
    CGO_ENABLED = '1'
  }
  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("${obltGitHubComments()}")
  }
  stages {
    stage('Checkout') {
      steps {
        pipelineManager([ cancelPreviousRunningBuilds: [ when: 'PR' ] ])
        deleteDir()
        gitCheckout(basedir: "${BASE_DIR}", githubNotifyFirstTimeContributor: true)
        stash allowEmpty: true, name: 'source', useDefaultExcludes: false
        dir("${BASE_DIR}"){
          setEnvVar('GO_VERSION', readFile(".go-version").trim())
        }
      }
    }
	  stage('Lint'){
      steps {
        withGithubNotify(context: "Check") {
          dir("${BASE_DIR}"){
            withMageEnv(version: "${env.GO_VERSION}"){
              sh(label: 'Mage check', script: 'mage -v check')
            }
          }
        }
      }
    }
    stage('Test') {
      failFast false
      matrix {
        agent {label "${PLATFORM}"}
        options { skipDefaultCheckout() }
        environment {
          HOME = "${env.WORKSPACE}"
        }
        axes {
          axis {
            name 'PLATFORM'
            values 'ubuntu-20.04 && immutable', 'windows-2019 && windows-immutable', 'darwin && orka && x86_64'
          }
        }
        stages {
          stage('Test') {
            steps {
              withGithubNotify(context: "Test-${PLATFORM}") {
                deleteDir()
                unstash 'source'
                dir("${BASE_DIR}"){
                  withGoEnv(){
                    goTestJUnit(options: '-v ./...', output: 'junit-report.xml')
                  }
                }
              }
            }
            post {
              always {
                junit(allowEmptyResults: true, keepLongStdio: true, testResults: '**/junit-report.xml')
              }
            }
          }
        }
      }
    }
  }
  post {
    cleanup {
      notifyBuildResult(prComment: true)
    }
  }
}
