pipeline {
  agent any
  options {
    timestamps()
    ansiColor('xterm')
  }

  stages {
    stage('build') {
      parallel {
        stage('build:go') {
          agent { docker { image 'docker.internal.justin.tv/devtools/bionic/go1.11.3' } }
          steps {
            withCredentials([[
              $class: 'AmazonWebServicesCredentialsBinding',
              credentialsId: 'team-sse-jenkins'
            ]]) {
              sh 'make setup-jenkins-go build-go'
            }
            stash name: 'coverage', includes: 'coverage.txt'
            stash name: 'bin', includes: 'bin/*'
            stash name: 'lambdas', includes: 'build/lambdas/*.zip'
          }
        }
        stage('test-e2e:go') {
          agent { docker { image 'docker.internal.justin.tv/devtools/bionic/go1.11.3' } }
          steps {
            withCredentials([[
              $class: 'AmazonWebServicesCredentialsBinding',
              credentialsId: 'team-sse-jenkins'
            ]]) {
              sh 'make setup-jenkins-go test-e2e-go'
            }
          }
        }
      }
    }

    stage('build:docker') {
      steps {
        unstash name: 'bin'
        sh 'make build-docker'
      }
    }

    stage('push:coverage') {
      steps {
        unstash name: 'coverage'
        withCredentials([
          [$class: 'StringBinding', credentialsId: 'beefcake-server-codecov-token', variable: 'CODECOV_TOKEN']
        ]) {
          sh 'make upload-coverage'
        }
      }
    }

    stage('deploy:testing') {
      when { branch 'dev' }
      steps {
        unstash name: 'lambdas'
        unstash name: 'bin'
        withCredentials([[
          $class: 'AmazonWebServicesCredentialsBinding',
          credentialsId: 'team-sse-jenkins'
        ]]) {
          sh 'make deploy environment=testing'
        }
      }
    }

    stage('deploy:staging') {
      when { expression { BRANCH_NAME ==~ /^release\/.+$/ } }
      steps {
        unstash name: 'lambdas'
        unstash name: 'bin'
        withCredentials([[
          $class: 'AmazonWebServicesCredentialsBinding',
          credentialsId: 'team-sse-jenkins'
        ]]) {
          sh 'make deploy environment=staging'
        }
      }
    }

    stage('deploy:production') {
      when { branch 'master' }
      steps {
        unstash name: 'lambdas'
        unstash name: 'bin'
        withCredentials([[
          $class: 'AmazonWebServicesCredentialsBinding',
          credentialsId: 'team-sse-jenkins'
        ]]) {
          sh 'make deploy environment=production'
        }
      }
    }
  }
}
