#!/usr/bin/env groovy

@Library('apm@current') _

pipeline {
  agent { label 'linux && immutable' }
  environment {
    REPO = 'ecs-logging-python'
    BASE_DIR = "src/go.elastic.co/apm/${env.REPO}"
    NOTIFY_TO = credentials('notify-to')
  }
  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('Lint') {
      options { skipDefaultCheckout() }
      steps {
        withGithubNotify(context: 'Lint') {
          deleteDir()
          unstash 'source'
          dir("${BASE_DIR}"){
            preCommit(commit: "${GIT_BASE_COMMIT}", junit: true)
          }
          python(version: '3.7') {
            sh('.ci/scripts/lint.sh')
          }
        }
      }
    }
    stage('Test') {
      matrix {
        agent { label 'linux && immutable' }
        axes {
          axis {
            name 'VERSION'
            values '2.7', '3.5', '3.6', '3.7', '3.8'
          }
        }
        stages {
          stage('Test') {
            options { skipDefaultCheckout() }
            steps {
              withGithubNotify(context: "Test ${VERSION}") {
                deleteDir()
                unstash 'source'
                python(version: VERSION) {
                  sh(".ci/scripts/test.sh ${VERSION}")
                }
              }
            }
            post {
              always {
                junit(allowEmptyResults: true, keepLongStdio: true, testResults: "${BASE_DIR}/junit*.xml")
              }
            }
          }
        }
      }
    }
  }
  post {
    cleanup {
      notifyBuildResult()
    }
  }
}

def python(Map v = [:], body) {
  def dockerImage = v.version.equals('2.7') ? 'python:3.7' : "python:${v.version}"
  // If dockerhub got issues then let's retry twice
  retry(2) {
    sleep 5
    sh "docker pull ${dockerImage}"
  }
  docker.image(dockerImage).inside("-e HOME=${env.WORKSPACE}"){
    dir("${BASE_DIR}"){
      body()
    }
  }
}