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

  environment {
    PKG = 'code.justin.tv/foundation/history-edge'
    REPO = 'docker-registry.internal.justin.tv/foundation-history-edge'
  }

  stages {
    stage('lint') {
      parallel {
        stage('lint-tf') {
          agent { docker { image 'hashicorp/terraform' } }
          steps {
            sh 'terraform fmt -check terraform'
          }
        }
      }
    }

    stage('build') {
      agent { docker { image 'docker-registry.internal.justin.tv/devtools/bionic/go1.11.4' } }
      steps {
        sh 'mkdir -p $(dirname $GOPATH/src/$PKG)'
        sh 'cp -r $(pwd) $GOPATH/src/$PKG'
        sh 'go get github.com/twitchtv/retool'
        sh 'retool build'
        sh 'retool do gometalinter $GOPATH/src/$PKG/... --vendor'
        sh 'cd $GOPATH/src/$PKG'
        sh 'go build -o ./bin/deploy $PKG/scripts'
        stash name: 'bin', includes: 'bin/*'
      }
    }

    stage('build-docker') {
      steps {
        sh 'docker build -t $REPO/prod:$GIT_COMMIT --target nginx-prod .'
        sh 'docker push $REPO/prod:$GIT_COMMIT'

        sh 'docker build -t $REPO/staging:$GIT_COMMIT --target nginx-staging .'
        sh 'docker push $REPO/staging:$GIT_COMMIT'
      }
    }

    stage('deploy-staging') {
      when { branch 'dev' } 
      steps {
        unstash name: 'bin'
        withCredentials([
          [$class: 'StringBinding', credentialsId: 'aws-history-edge-staging-access-key', variable: 'AWS_ACCESS_KEY_ID'],
          [$class: 'StringBinding', credentialsId: 'aws-history-edge-staging-secret-key', variable: 'AWS_SECRET_ACCESS_KEY'],
        ]) {
          sh 'ENVIRONMENT="staging" bash ./scripts/deploy.sh'
        }
      }
    }

    stage('deploy-production') {
      when { branch 'master' }
      steps {
        unstash name: 'bin'
        withCredentials([
          [$class: 'StringBinding', credentialsId: 'aws-history-edge-prod-access-key', variable: 'AWS_ACCESS_KEY_ID'],
          [$class: 'StringBinding', credentialsId: 'aws-history-edge-prod-secret-key', variable: 'AWS_SECRET_ACCESS_KEY'],
        ]) {
          sh 'ENVIRONMENT="prod" bash ./scripts/deploy.sh'
        }
      }
    }
  }
}
