#!/usr/bin/env groovy

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

  environment {
    AWS_DEFAULT_REGION = 'us-west-2'
  }

  stages {
    stage('Upload Powershell Artifacts') {
      when { not { changeRequest() } } // only build on branch, not PR - prevent duplicates
      steps {
        withAWS(role: "jenkins_grid_artifact_upload", roleAccount: "147030575244", region: "us-west-2") {
          sh """
          |export GIT_BRANCH=\$GIT_BRANCH
          |./src/node/windows/10/build/provisioner/upload_to_s3.sh
        """.stripMargin()
        }
      }
    }

    stage('Chef: Lint') {
      when { not { changeRequest() } } // only build on branch, not PR - prevent duplicates
      steps {
        sh """
          |./src/node/windows/10/build/provisioner/lint_chef.sh
        """.stripMargin()
      }
    }

    stage('Chef: Upload Artifacts') {
      when { not { changeRequest() } } // only build on branch, not PR - prevent duplicates
      steps {
        withAWS(role: "jenkins_grid_artifact_upload", roleAccount: "147030575244", region: "us-west-2") {
          sh """
          |export GIT_BRANCH=\$GIT_BRANCH
          |./src/node/windows/10/build/provisioner/build_upload_chef.sh
        """.stripMargin()
        }
      }
    }

    // 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') {
          echo 'Deploying code to staging environment'
          build job: 'browser-grid-win10-deploy', propagate: true, wait: true, \
            parameters: [ \
              string(name: 'GRID_CLUSTER_ID', value: '2z9oaf6z'), \
              string(name: 'GRID_ENVIRONMENT', value: 'dev'), \
              string(name: 'GRID_HUB_ENVIRONMENT', value: 'dev-ato'), \
              string(name: 'GRID_BRANCH', value: "$CHANGE_BRANCH"), \
              string(name: 'AWS_DEFAULT_REGION', value: "$AWS_DEFAULT_REGION"), \
            ]

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

  post {
    always {
      cleanWs()
    }
  }
}
