#!groovy
@Library('infraLib') _

def testSummary

pipeline {

  agent {
    label 'linux-agents-xlarge'
  }

  options {
    timeout(time: 60, unit: 'MINUTES')
    buildDiscarder logRotator(
      artifactDaysToKeepStr: '',
      artifactNumToKeepStr: '',
      daysToKeepStr: '',
      numToKeepStr: '5')
    disableResume()
    disableConcurrentBuilds()
    ansiColor('xterm')
    copyArtifactPermission '*'
  }

  parameters {
    string (
            defaultValue: '',
            description: 'Copy allure report from this build',
            name: 'PREVIOUS_ALLURE_RESULTS_BUILD_NUMBER',
            trim: true
    )
  }

  environment {
    USER_EMAIL    = utility.getSecretValueById('infra/jenkins/apollo/dev/uitest/USER_EMAIL', "gdb-delphi-dev")
    USER_PASSWORD = utility.getSecretValueById('infra/jenkins/apollo/dev/uitest/USER_PASSWORD', "gdb-delphi-dev")

    HEADLESS = 'True'

    NOTIFICATIONS_CHANNEL = '#apollo-test-reports'

    TARGET_API_URL  = "https://qa-proxy.apollo.stream"
    ENV_BASE_URL    = "https://qa.apollo.stream"

    AUTH0_CLIENT_ID     = utility.getSecretValueById('infra/jenkins/apollo/dev/uitest/CLIENT_ID', "gdb-delphi-dev")
    AUTH0_CLIENT_SECRET = utility.getSecretValueById('infra/jenkins/apollo/dev/uitest/CLIENT_SECRET', "gdb-delphi-dev")
    AUTH0_REALM         = 'LevelDB'
    AUTH0_GRANT_TYPE    = 'http://auth0.com/oauth/grant-type/password-realm'
    AUTH0_AUDIENCE      = 'https://apollo-private-api/'
    AUTH0_HOST          = 'https://sme-dna.auth0.com/oauth/token'

    PYTEST_XDIST_WORKER = 'master'
    UI_TESTS = ''
    THREADS  = 5

    AWS_ACCOUNT_ID = '725764004555'
    AWS_REGION     = 'us-east-1'

    ECR_REGISTRY        = "${env.AWS_ACCOUNT_ID}.dkr.ecr.${env.AWS_REGION}.amazonaws.com"
    ECR_REPOSITORY_NAME = 'apollo/ui-test-playwright'
    ECR_REGISTRY_URI    = "${ECR_REGISTRY}/${ECR_REPOSITORY_NAME}"

    REVISION = "${sh script: 'git rev-parse --short=8 HEAD', returnStdout: true}".trim()
  }

  stages {
    stage('Notify start') {
      steps {
        script {
          utility.slackNotify(
            currentBuild.currentResult,
            env.NOTIFICATIONS_CHANNEL,
            "started ${env.JOB_NAME} <${env.BUILD_URL}|Open>"
          )
        } /** end: script */
      } /** end: steps */
    } /** end: stage */

    stage('Build') {
      when {
        not { expression { return params.USE_CACHE } }
      }
      steps {
        sh label: 'build docker image', script: 'make docker/image/build'
      } /** end: steps */
    } /** end: stage */

    stage('Push') {
      when {
        allOf {
          not { expression { return params.USE_CACHE } }
          // branch 'master'
        }
      }
      steps {
        sh label: 'push docker image', script: 'make docker/image/push'
      } /** end: steps */
    } /** end: stage */

    stage('Pull') {
      when {
        allOf {
          expression { return params.USE_CACHE }
          // branch 'master'
        }
      }
      steps {
        sh label: 'pull docker image', script: 'make docker/image/pull'
      } /** end: steps */
    } /** end: stage */

    stage('Test') {
      stages{
        stage('Copy Allure report') {
          when {
            not { expression { return  params.PREVIOUS_ALLURE_RESULTS_BUILD_NUMBER.equals('') } }
          }
          steps {
            script {
              copyArtifacts filter: 'output/allure_report/*',
                            fingerprintArtifacts: true,
                            projectName: currentBuild.fullProjectName,
                            selector: specific("${params.PREVIOUS_ALLURE_RESULTS_BUILD_NUMBER}")
            }
          }
        }
        stage('Test') {
          steps {
            withDockerContainer(args: "--entrypoint=''", image: "${ECR_REGISTRY_URI}:${env.REVISION}") {
               script {
                   def data = "ENV=${env.ENV_BASE_URL}\nTHREADS=${env.THREADS}"
                   writeFile(file: 'output/allure_report/environment.properties', text: data)
                   sh "ls -l"
               }
              script {
                ui_test_cmd = []
                ui_test_cmd << ('pytest')
                ui_test_cmd << ('--html=output/report.html')
                ui_test_cmd << ('--self-contained-html')
                ui_test_cmd << ('--alluredir=output/allure_report')
                ui_test_cmd << ('--reruns 2')
                ui_test_cmd << ("-n ${env.THREADS}")
                ui_test_cmd << ('src/tests/')
                echo ui_test_cmd.join(' ')
                sh label: 'run ui tests', script: ui_test_cmd.join(" ")
              } /** end: script */

            } /** end: withDockerContainer */
          } /** end: steps */
          post {
            always {
              sh 'mkdir -p output/ && sudo chown ec2-user:ec2-user -R output/ && ls -l output/'
              script {
                publishHTML target: [
                              allowMissing         : false,
                              alwaysLinkToLastBuild: false,
                              keepAll              : true,
                              reportDir            : '',
                              reportFiles          : 'output/report.html',
                              reportName           : 'Playwright report',
                            ]
                allure([
                  includeProperties: false,
                  jdk              : '',
                  properties       : [],
                  reportBuildPolicy: 'ALWAYS',
                  results          : [[path: 'output/allure_report']]
                ])
                archiveArtifacts artifacts: 'output/allure_report/*'
                script { testSummary = utility.getAllureTestSummary(env.BUILD_URL) }
              } /** end: script */
            } /** end: always */
          } /** end: post */
        } /** end: stage */
      } /** end: stages */
    } /** end: stage */
  } /** end: stages */
  post {
    success {
      script { utility.slackNotify('SUCCESS', env.NOTIFICATIONS_CHANNEL, 'ignored', testSummary) }
    } /** end: success */
    failure {
      script { utility.slackNotify('FAILURE', env.NOTIFICATIONS_CHANNEL, 'ignored', testSummary) }
    } /** end: unsuccessful */
    unstable {
      script { utility.slackNotify('UNSTABLE', env.NOTIFICATIONS_CHANNEL, 'ignored', testSummary) }
    } /** end: unsuccessful */
    always {
      script {
        utility.slackNotify(
          currentBuild.currentResult,
          env.NOTIFICATIONS_CHANNEL,
          "finished ${env.JOB_NAME} <${env.BUILD_URL}|Open>"
        )
      } /** end: script */
    } /** end: always */
  } /** end: post */
} /** end: pipeline */
