@Library('flexo-libs')_

// CHANGE THE FOLLLOWING ACCOUNTS WHEN FORKING
ACCOUNT_IDS = [
  "355334781110", // twitch-video-coreservices+metrics-prod-us-west-2
]

PROJECT_NAME = "statsd-proxy" // The name of the ECR repo
JENKINS_ROLE = "jenkins-to-ecr-metrics-role" // The name of the IAM role that Jenkins can assume
AWS_REGION   = "us-west-2"

properties([
  pipelineTriggers([
    [$class: "tv.justin.jenkins.twitchgithub.GitHubPushTrigger"]
  ])
])

pipeline {
  agent any

  options {
    disableConcurrentBuilds()
    timeout(time: 10, unit: 'MINUTES')
    ansiColor('xterm')
    timestamps()
  }

  stages {
    stage("Build") {
      steps {
        sh "docker build --target=build ."
      }
    }

    stage("Publish") {
      when {
        branch "master"
      }

      steps {
        sh "docker build -t ${PROJECT_NAME} ."

        script {
          tag = commitSHA()
        }

        pushImage(ACCOUNT_IDS, tag)
      }
    }
  }
}


String commitSHA() {
  return sh(script: "git rev-parse --short HEAD", returnStdout: true).trim()
}

String repositoryURL(String accountID) {
  return "${accountID}.dkr.ecr.${AWS_REGION}.amazonaws.com/${PROJECT_NAME}".toString()
}

def pushImage(ArrayList account_ids, String tag) {
  account_ids.each { account ->
    url = repositoryURL(account)

    sh "docker tag ${PROJECT_NAME} ${url}:${tag}"

    withAgentAWS(role: JENKINS_ROLE, roleAccount: account, region: AWS_REGION) {
      sh "\$(aws ecr get-login --no-include-email --region ${AWS_REGION})"
      sh "aws ecr describe-images --region=us-west-2 --repository-name=${PROJECT_NAME} --image-ids imageTag=bootstrap || docker tag ${PROJECT_NAME} ${url}:bootstrap"
      sh "docker push ${url}"
    }
  }
}
