#!/usr/bin/env groovy

@Library('apm@current') _

pipeline {
  agent { label 'ubuntu-20 && immutable' }
  environment {
    REPO = 'gosigar'
    BASE_DIR = "src/github.com/elastic/${env.REPO}"
    PIPELINE_LOG_LEVEL='INFO'
  }
  options {
    timeout(time: 1, unit: 'HOURS')
    buildDiscarder(logRotator(numToKeepStr: '10', artifactNumToKeepStr: '10', 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)?|/test).*')
  }
  stages {
    stage('Checkout') {
      steps {
        deleteDir()
        gitCheckout(basedir: "${BASE_DIR}")
        stash allowEmpty: true, name: 'source', useDefaultExcludes: false
      }
    }
    stage('Lint'){
      steps {
        withGoEnv(){
          dir("${BASE_DIR}"){
            sh(label: 'lint', script: '''
              go mod tidy && git diff --exit-code
              gofmt -l . | read && echo "Code differs from gofmt's style. Run 'gofmt -w .'" 1>&2 && exit 1 || true
            ''')
            sh(label: 'Go vet', script: 'go vet')
          }
        }
      }
    }
    stage('Build and test'){
      matrix {
        agent {label "${PLATFORM}"}
        axes {
          axis {
            name 'GO_VERSION'
            values '1.15.8', '1.16'
          }
          axis {
            name 'PLATFORM'
            values 'macosx&&x86_64', 'macosx&&arm64', 'ubuntu-20 && immutable', 'windows-2012-r2 && windows-immutable'
          }
        }
        excludes {
          exclude {
            axis {
              name 'GO_VERSION'
              values '1.15.8'
            }
            axis {
              name 'PLATFORM'
              values 'macosx&&arm64'
            }
          }
          exclude {
            axis {
              name 'GO_VERSION'
              values '1.16'
            }
            axis {
              name 'PLATFORM'
              notValues 'macosx&&arm64'
            }
          }
        }
        stages {
          stage('build'){
            steps {
              deleteDir()
              unstash 'source'
              withGoEnv(version: env.GO_VERSION){
                dir("${BASE_DIR}"){
                  cmd(label: 'Go build', script: 'go build')
                }
              }
            }
          }
          stage('test'){
            steps {
              withGoEnv(version: env.GO_VERSION){
                dir("${BASE_DIR}"){
                  goTestJUnit(options: '-v ./...', output: 'junit-report.xml')
                  buildExamples()
                }
              }
            }
            post{
              cleanup{
                junit(testResults: "${BASE_DIR}/junit-report.xml", allowEmptyResults: true)
              }
            }
          }
        }
      }
    }
  }
  post {
    cleanup {
      notifyBuildResult(prComment: true)
    }
  }
}

def getExamplesDirs(){
  return [
    "examples/df",
    "examples/free",
    "examples/ps",
    "examples/uptime"
  ]
}

def buildExamples(){
  getExamplesDirs().each { exampleDir ->
      cmd(label: "Build Example ${exampleDir}", script: "go build -o ${exampleDir}/out.exe ./${exampleDir}")
      dir("${exampleDir}"){
        def prefix = ''
        if(isUnix()){
          prefix = './'
        }
        cmd(label: "Running Example ${exampleDir}", script: "${prefix}out.exe")
      }
  }
}
