@Library('flexo-libs')_

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

GRAPHITE_WEB_LOCAL_REPO = 'video-coreservices/graphite-web'
GRAPHITE_WEB_VERSION = "1ca8e602c15ba9ed7737976d01c9d1ba10eafa40"
AWS_REGION = 'us-west-2'

JENKINS_ROLE = "graphite-web-jenkins-to-ecr-metrics-role"

String repositoryURL(String account_id, String project_name) {
  return "${account_id}.dkr.ecr.${AWS_REGION}.amazonaws.com/${project_name}".toString()
}

def pushImages(ArrayList account_ids, String source, String project_name, String tag) {
  account_ids.each { account ->
    target = repositoryURL(account, project_name)

    sh "docker tag ${source} ${target}:${tag}"

    withAgentAWS(role: JENKINS_ROLE, roleAccount: account, region: AWS_REGION) {
      sh "\$(aws ecr get-login --region ${AWS_REGION} --no-include-email)"
      sh "docker push ${target}:${tag}"
    }
  }
}

pipeline {
  agent any

  options {
    disableConcurrentBuilds()
    timeout(time: 1, unit: 'HOURS')
    ansiColor('xterm')
    timestamps()
  }

  stages {
    stage('Build graphite-web docker image') {
      steps {
        sshagent(credentials: ['git-aws-read-key']) {
          sh "docker build -t ${GRAPHITE_WEB_LOCAL_REPO} --build-arg version=${GRAPHITE_WEB_VERSION} ./graphite-web"
        }
      }
    }
    stage('Push docker images to ECRs') {
      when {
       branch 'master'
      }
      steps {
        pushImages(ACCOUNT_IDS, GRAPHITE_WEB_LOCAL_REPO, 'graphite_web', GRAPHITE_WEB_VERSION)
      }
    }
  }
}
