#!groovy
@Library('infraLib') _

pipeline {
  agent {
    label 'linux-agents-xlarge'
  }
  options {
    // timeout(time: 600, unit: 'MINUTES') // disable timeout 
    disableConcurrentBuilds()
    ansiColor('xterm')
    buildDiscarder logRotator(artifactDaysToKeepStr: '', artifactNumToKeepStr: '', daysToKeepStr: '', numToKeepStr: '30')
  }
  environment {
    NOTIFICATIONS_CHANNEL='#rti-test-reports'
  }
  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 & Test') {
      environment {
        UI_FRAMEWORK_PKG_VER = '1.2.6'

        PYTEST_XDIST_WORKER = 'master'
        SELENIUM_HEADLESS   = 'True'
        SELENIUM_ENV        = 'web'
        CHROMEDRIVER_PATH   = 'path'
        SELENOID_HOST       = 'selinoid'
        BROWSER_NAME        = 'chrome'
        SELENIUM_TIMEOUT    = 100
        AWS_PROFILE         = 'gdb-delphi-dev'

        AUTH0_CLIENT_ID     = 'placeholder'
        AUTH0_CLIENT_SECRET = 'placeholder'
        AUTH0_AUDIENCE      = 'placeholder'
        AUTH0_GRANT_TYPE    = 'placeholder'
        AUTH0_REALM         = 'placeholder'
        AUTH0_HOST          = 'placeholder'
        USER_EMAIL          = 'placeholder'
        USER_PASSWORD       = 'placeholder'
        MYSQL_DB_NAME       = 'placeholder'
        MYSQL_DB_HOST       = 'placeholder'
        MYSQL_DB_USER       = 'placeholder'
        MYSQL_DB_PASS       = 'placeholder'
        TARGET_API_URL      = 'placeholder'
        ENV_BASE_URL        = 'https://delphi-datavalidation.delphiplatform.io/artist'

        BROWSER_LATEST_TAG = sh(returnStdout: true, script: "curl -s https://registry.hub.docker.com/v1/repositories/selenoid/vnc/tags | jq -r .[].name | grep ${env.BROWSER_NAME} | tail -n1").trim()
        BROWSER_LATEST_VER = sh(returnStdout: true, script: "echo ${env.BROWSER_LATEST_TAG} | cut -f 2 -d_").trim()
      } /** end: environment */
      steps {
        script {
          sh """
          aws ecr get-login --no-include-email --profile ${env.AWS_PROFILE} --region us-east-1 | awk '{print \$6}' | docker login -u AWS --password-stdin https://475275892927.dkr.ecr.us-east-1.amazonaws.com
          docker pull selenoid/vnc:${env.BROWSER_LATEST_TAG}
          docker pull 475275892927.dkr.ecr.us-east-1.amazonaws.com/apollo/ui-test-selinoid-runner:${env.UI_FRAMEWORK_PKG_VER}
          mkdir selenoid_logs
          """
          docker.image('aerokube/selenoid:latest-release').withRun("-p 4444:4444 --entrypoint /entrypoint.sh -e BROWSER_NAME=${env.BROWSER_NAME} -e BROWSER_LATEST_VER=${env.BROWSER_LATEST_VER} -v ${env.WORKSPACE}/selenoid_logs:/tmp/logs -v /var/run/docker.sock:/var/run/docker.sock -v ${env.WORKSPACE}/entrypoint.sh:/entrypoint.sh:ro") { c ->
            docker.image("475275892927.dkr.ecr.us-east-1.amazonaws.com/apollo/ui-test-selinoid-runner:${env.UI_FRAMEWORK_PKG_VER}").inside("--link ${c.id}:selinoid") {
              sh '''
              set +e
              while ! curl -q selinoid:4444; do sleep 1; done
              py.test --html=report.html --self-contained-html --alluredir=app/src/allure_report app/src/tests/test_data/ --reruns 2 -n 3
              ls -ashil       
              '''
            } /** end: docker.image */
          } /** end: docker.image */
        } /** end: script */
      } /** end: steps */
      post {
        always {
          sh "ls -ashil"
          script {
            publishHTML target: [
                    allowMissing         : false,
                    alwaysLinkToLastBuild: false,
                    keepAll              : true,
                    reportDir            : '',
                    reportFiles          : 'report.html',
                    reportName           : 'Selenoid report',
            ]
            files = findFiles(glob: '*.csv')
            files.each {
              slackUploadFile channel: env.NOTIFICATIONS_CHANNEL, filePath: it.path, initialComment: it.path
            }
          } /** end: script */
        } /** end: always */
      } /** end: post */
    } /** end: stage */
  } /** end: stages */
  post {
    always {
      script {
        utility.slackNotify(
          currentBuild.currentResult,
          env.NOTIFICATIONS_CHANNEL,
          "finished ${env.JOB_NAME} <${env.BUILD_URL}|Open>"
        )
      } /** end: script */
    } /** end: always */
  } /** end: post */
}
