@Library('infraLib') _

def test_status = "missing"

def getEnvList(){
   switch (JOB_BASE_NAME) {
      case ~/delphi-qa-automation-(.*)/:
      	 SUBSTRINGS_JOB_BASE_NAME=JOB_BASE_NAME.split('-')
         ENV_NAME=SUBSTRINGS_JOB_BASE_NAME[-1..0]
         return [ENV_NAME[0].toLowerCase()]
         break
      default:
         return ['dev','qa','stage']
         break
   }
}

if (JOB_BASE_NAME.toLowerCase() == "delphi-qa-automation-dev") {
  properties([
    [$class: 'GithubProjectProperty',
    displayName: '',
    projectUrlStr: 'https://github.com/filtr/delphi-qa-automation.git'],
    pipelineTriggers([githubPush()])])
}

pipeline {
  agent {
    label 'linux-agents'
  }
  environment {
    REPORTSDIR_SHORT = "allure-results"
    NOTIFICATIONS_CHANNEL = 'delphi-autotests-status'
    AWS_PROFILE = "gdb-delphi-dev"
    ENVIRONMENT = "${params.ENVIRONMENT}"
    PROXY = "no"
  }
  parameters {
    choice(
      choices: getEnvList(),
      description: 'Set environment for deployment. Skipped by default for master/release*, dev by default for all other branches',
      name: 'ENVIRONMENT'
    )
  }
  stages {
    stage('Build test image') {
      environment { AWS_PROFILE="gdb-delphi-dev" }
      steps {
        sh 'make docker/build'
      }
    }
    stage('Create reports folder') {
      steps {
        sh "mkdir ${env.REPORTSDIR_SHORT}"
      }
    }
    stage('Docker stage') {
      agent {
        docker {
          image 'delphi-qa-automation:latest'
          // The following args are aimed to workaround some issues with using Docker container as a Jenkins agent:
          // 1. Disable image entrypoint to let Jenkins verify container was started correctly using custom commands.
          // 2. Explicitly tell SBT locations for configs and local cache because Jenkins runs container using a
          //    custom user (with `-u 1000:1000`) and SBT cannot resolve these paths automatically.
          // 3. Set MaxMetaspaceSize to 1G due to OOM
          args "--entrypoint '' -v ${env.HOME}/.aws:/app/.aws -v ${env.WORKSPACE}/${env.REPORTSDIR_SHORT}:/app/${env.REPORTSDIR_SHORT}"
          reuseNode true
        }
      }
      stages {
        stage('Install dependencies') {
          steps {
            sh "make venv"
          }
        }
        stage('Run the tests') {
          environment {
            REPORTSDIR = "/app/${env.REPORTSDIR_SHORT}"
          }
          steps {
            sh "make test | tee log.txt"
            script {
              test_status = sh(script: "cat log.txt | egrep '=.*(failed)?.*(passed)?.*(deselected)?.*(warnings)? in .*=' | tr -d '='", returnStdout: true).trim()
            }
          }
        }
      }
    }
  }
  post {
    always {
      sh "sudo chown -R ec2-user:ec2-user ${env.WORKSPACE}"
      script{
        allure([
          includeProperties: false,
          jdk: '',
          properties: [],
          reportBuildPolicy: 'ALWAYS',
          results: [[path: "${env.WORKSPACE}/${env.REPORTSDIR_SHORT}"]]
        ])
      }
    }
    success {
      slackSend (
        channel: "${env.NOTIFICATIONS_CHANNEL}",
        iconEmoji: ':rocket:',
        color: "good",
        message: "Environment: ${params.ENVIRONMENT} <${env.BUILD_URL}/allure/|${env.JOB_NAME}>\n${test_status}"
      )
    }
    unsuccessful {
      slackSend (
        channel: "${env.NOTIFICATIONS_CHANNEL}",
        iconEmoji: ':flying_saucer:',
        color: "danger",
        message: "Environment: ${params.ENVIRONMENT} <${env.BUILD_URL}/allure/|${env.JOB_NAME}>\n${test_status}"
      )
    }
  }
}
