#!/usr/bin/env groovy

@Library('jenkins@master')
beanstalkHelper = new tv.justin.qe.ElasticBeanstalk()

pipeline {
  agent any
  options {
    timeout(time: 6, unit: 'HOURS')
    timestamps()
    ansiColor('xterm')
  }

  environment {
    AWS_DEFAULT_REGION = 'us-west-2'
    EB_APP_NAME = 'grid-hub'
  }

  stages {
    stage('Publish Artifact') {
      when { not { changeRequest() } } // only publish on branch, not PR - prevent duplicates
      steps {
        script {
          sh './scripts/upload_artifacts.sh'
        }
      }
    }

    // Need to combine Deploy & Integration Test stages as the lock needs to be applied across both
    stage('Deploy to Staging & Run Integration Tests') {
      when { changeRequest() }

      steps {
        // Lock to ensure another layer (router, hub, node) doesn't get deployed to mid-tests
        lock('browser_grid_integration_testing') {

          // Use AWS Credentials
          withCredentials([
            usernamePassword(credentialsId: 'twitch-cape-qe-aws', usernameVariable: 'AWS_ACCESS_KEY_ID', passwordVariable: 'AWS_SECRET_ACCESS_KEY'),
          ]) {
            script {
              timeout(5) { // timeout after 5 minutes
                sh './scripts/ci_wait_for_app_version.sh'
              }
            }
          }

          echo 'Deploying code to staging environment'
          build job: 'qe-grid-hub-deploy', propagate: true, wait: true, \
            parameters: [ \
              string(name: 'GIT_COMMIT', value: "$GIT_COMMIT"), \
              string(name: 'ENVIRONMENT', value: 'dev-ato-2z9oaf6z') \
            ]

          echo 'Running integration tests'
          build job: 'browser-grid-tc-trigger', propagate: true, wait: true
        }
      }
    }
  }
  post {
    always {
      cleanWs()
    }
  }
}
