#!/usr/bin/env groovy

@Library('apm@current') _

pipeline {
  agent { label 'ubuntu-18 && immutable' }
  environment {
    REPO="fleet-server"
    BASE_DIR="src/github.com/elastic/${env.REPO}"
    DOCKER_COMPOSE_VERSION = '1.25.5'
    JOB_GIT_CREDENTIALS = "f6c7695a-671e-4f4f-a331-acdce44ff9ba"
    PIPELINE_LOG_LEVEL='INFO'
  }
  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)?.*|^\\/test$)')
  }
  stages {
    /**
     Checkout the code and stash it, to use it on other stages.
     */
    stage('Checkout') {
      steps {
        deleteDir()
        gitCheckout(basedir: "${BASE_DIR}")
        stash allowEmpty: true, name: 'source', useDefaultExcludes: false
      }
    }
    stage('Check') {
      steps {
        cleanup()
        dir("${BASE_DIR}"){
          withGoEnv(){
            sh(label: 'check',script: 'make check')
          }
        }
      }
    }
    stage('Local') {
      steps {
        cleanup()
        dir("${BASE_DIR}"){
          withGoEnv(){
            sh(label: 'local',script: 'make local')
          }
        }
      }
    }
    stage('Unit Test') {
      options { skipDefaultCheckout() }
      steps {
        cleanup()
        dir("${BASE_DIR}"){
          withGoEnv(){
            sh(label: 'test', script: 'make test-unit')
            sh(label: 'test', script: 'make junit-report')
          }
        }
      }
      post {
        always {
          junit(allowEmptyResults: true, keepLongStdio: true, testResults: "${BASE_DIR}/build/*.xml")
        }
      }
    }
    stage('Integration Test') {
      options { skipDefaultCheckout() }
      steps {
        cleanup()
        dir("${BASE_DIR}"){
          withGoEnv(){
            retryWithSleep(retries: 2, seconds: 5, backoff: true){ sh(label: "Install Docker", script: '.ci/scripts/install-docker-compose.sh') }
            sh(label: 'test', script: 'make test-int')
            sh(label: 'test', script: 'make junit-report')
          }
        }
      }
      post {
        always {
          junit(allowEmptyResults: true, keepLongStdio: true, testResults: "${BASE_DIR}/build/*.xml")
        }
      }
    }
  }
  post {
    cleanup {
      notifyBuildResult(prComment: true)
    }
  }
}

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