#!/usr/bin/env groovy

@Library("infraLib") _

def testSummary
def tf_workspace = 'test6'

pipeline {
  agent {
    label 'linux-agents-2xlarge'
  }

  options {
    disableConcurrentBuilds()
    disableResume()
    buildDiscarder logRotator(artifactDaysToKeepStr: '', artifactNumToKeepStr: '', daysToKeepStr: '', numToKeepStr: '5')
    ansiColor("xterm")
    timeout(time: 8, unit: 'HOURS')
  }

  triggers {
    cron 'H 3 * * * '
  }

  parameters {
    separator name: 'separator-decibel-ui-test-endpoints', sectionHeader: 'Endpoints'
    string(defaultValue: "https://${tf_workspace}.decibel.stream/", description: "UI URL", name: "BASE_URL", trim: true)
    string(defaultValue: "master", description: "UI BRANCH OR PR", name: "UI_BRANCH", trim: true)
    string(defaultValue: "https://${tf_workspace}.decibel.stream/api/", description: "API URL", name: "API_URL", trim: true)
    string(defaultValue: "release", description: "API BRANCH OR PR", name: "API_BRANCH", trim: true)
  }

  environment {
    BASE_URL      = "${params.BASE_URL}"
    API_URL       = "${params.API_URL}"
    TIMEOUT_MS    = 180000
    ATLAS_AUTH_URL        = mctFrontendHelpers.getAtlasAuthUrlByEnv('stage')
    ATLAS_TOKEN_URL       = mctFrontendHelpers.getAtlasTokenUrlByEnv('stage')
    ATLAS_TOKEN_CLIENT_ID = mctFrontendHelpers.getAtlasTokenClientIdByEnv('stage')
    ATLAS_TOKEN_SECRET    = utility.getSecretValueByIdAndJsonPath('infra/jenkins/decibel/dev/uitest/ATLAS_TOKEN_SECRET', 'gdb-infra-dev', '."stage"')

    USER1_PASS   = utility.getSecretValueByIdAndJsonPath('infra/jenkins/decibel/dev/uitest/USER_CREDENTIALS', 'gdb-infra-dev', '."decibel.automation.root+1@techery.io"')
    USER2_PASS   = utility.getSecretValueByIdAndJsonPath('infra/jenkins/decibel/dev/uitest/USER_CREDENTIALS', 'gdb-infra-dev', '."decibel.automation.root+2@techery.io"')
    USER3_PASS   = utility.getSecretValueByIdAndJsonPath('infra/jenkins/decibel/dev/uitest/USER_CREDENTIALS', 'gdb-infra-dev', '."decibel.automation.root+3@techery.io"')
    USER4_PASS   = utility.getSecretValueByIdAndJsonPath('infra/jenkins/decibel/dev/uitest/USER_CREDENTIALS', 'gdb-infra-dev', '."decibel.automation.root+4@techery.io"')
    USER5_PASS   = utility.getSecretValueByIdAndJsonPath('infra/jenkins/decibel/dev/uitest/USER_CREDENTIALS', 'gdb-infra-dev', '."decibel.automation.root+5@techery.io"')
    USER11_PASS  = utility.getSecretValueByIdAndJsonPath('infra/jenkins/decibel/dev/uitest/USER_CREDENTIALS', 'gdb-infra-dev', '."decibel.automation.root+11@techery.io"')
    USER13_PASS  = utility.getSecretValueByIdAndJsonPath('infra/jenkins/decibel/dev/uitest/USER_CREDENTIALS', 'gdb-infra-dev', '."decibel.automation.root+13@techery.io"')
    USER14_PASS  = utility.getSecretValueByIdAndJsonPath('infra/jenkins/decibel/dev/uitest/USER_CREDENTIALS', 'gdb-infra-dev', '."decibel.automation.root+14@techery.io"')
    DEFAULT_USER = 'user13'

    WORK_DIR = "${env.WORKSPACE}/automation"

    COMPOSE_PROJECT_NAME = "ui-test-${env.BUILD_NUMBER}"

    NOTIFICATIONS_CHANNEL = "#decibel-automation-reports"

    CI = "1"

    PROJECT_KEY = 'DEC'
  }

  stages {
    stage("Launch API and UI") {
      steps {
        build job: "/Decibel/deploy-infra", parameters: [
          string(name: 'TF_WORKSPACE', value: "${tf_workspace}"),
          string(name: 'TF_VAR_api_branch', value: "${params.API_BRANCH}"),
          string(name: 'TF_VAR_ui_branch', value: "${params.UI_BRANCH}"),
          booleanParam(name: 'CREATE_DB', value: true)
        ]
      } /** end: steps */
    }
    stage("Test") {
      steps {
        sh label: "test", script: """
          cd ${env.WORK_DIR} && docker-compose up --build tests
        """
      }
      post {
        always {
          sh "sudo chown -R \$(whoami):\$(whoami) ${env.WORKSPACE}/"
          junit allowEmptyResults: true, testResults: "automation/playwright-report/index.xml"
          script {  testSummary = utility.getTestSummary() }
          publishHTML([allowMissing: true,
                       alwaysLinkToLastBuild: false,
                       keepAll: false,
                       reportDir: "automation/playwright-report/",
                       reportFiles: 'index.html',
                       reportName: 'HTML Report',
                       reportTitles: ''])
          sh "cd automation/ && zip -r playwright-report.zip playwright-report/"
          sh "cd automation/ && zip -r test-results.zip test-results/"
          archiveArtifacts artifacts: "automation/*.zip",
                           fingerprint: true,
                           followSymlinks: false,
                           onlyIfSuccessful: false
        }
      }
    }
  }
  post {
    always {
      build job: "/Decibel/destroy-infra", parameters: [
        string(name: 'TF_WORKSPACE', value: "${tf_workspace}")
      ]
      script {
        utility.slackNotify(
          currentBuild.result,
          env.NOTIFICATIONS_CHANNEL,
          "build ${currentBuild.result} \n${testSummary}\nArtifacts: \n${env.BUILD_URL}artifact/automation/test-results.zip \n${env.BUILD_URL}artifact/automation/playwright-report.zip"
        )
      }
    } /** end: always */
  } /** end: post */
} /** end: pipeline */

