#!/usr/bin/env groovy

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

def make(command) {
    sh "make ${command}"
}

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

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

  stages {
    stage('Test') {
      when { not { changeRequest() } } // only build on branch, not PR - prevent duplicates
      steps {
        sh 'manta -v'
        junit '.manta/test_report.xml'
      }
    }

    stage('Publish Results to Codecov') {
      when { not { changeRequest() } } // only on branch, not PR - prevent duplicates
      steps {
        make('ci-upload-coverage')
      }
    }

    stage('Publish Artifact') {
      when { not { changeRequest() } } // only publish on branch, not PR - prevent duplicates
      steps {
        withCredentials([
          usernamePassword(credentialsId: 'twitch-cape-qe-aws', usernameVariable: 'AWS_ACCESS_KEY_ID', passwordVariable: 'AWS_SECRET_ACCESS_KEY'),
        ]) {
          script {
            beanstalkHelper.cleanBeanstalkArtifacts('grid-router', 50)
            beanstalkHelper.createBeanstalkArtifactFromDirectory('grid-router', "$GIT_COMMIT", "elasticbeanstalk-us-west-2-425992774280")
          }
        }
      }
    }

    // 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-router-deploy', propagate: true, wait: true, \
            parameters: [ \
              string(name: 'GIT_COMMIT', value: "$GIT_COMMIT"), \
              string(name: 'ENVIRONMENT', value: 'dev-ato') \
            ]

          echo 'Running integration tests'
          build job: 'browser-grid-tc-trigger', propagate: true, wait: true
        }
      }
    }
  }
}
