@Library('flexo-libs')_

DEV_ACCOUNT_IDS = [
  "094345592176", // twitch-video-coreservices+package-repo-dev-us-west-2@amazon.com
]
WEST_ACCOUNT_IDS = [
  "860022126695", // twitch-video-coreservices+package-repo-prod-us-west-2@amazon.com
]
EAST_ACCOUNT_IDS = [
  "157880998906", // twitch-video-coreservices+package-repo-prod-us-east-2@amazon.com
]

PACKAGE_REPO_LOCAL_REPO = 'video-coreservices/docker-nginx'
NGINX_VERSION = "v1.1.0"
WEST_AWS_REGION = 'us-west-2'
EAST_AWS_REGION = 'us-east-2'

JENKINS_ROLE = "package-repo-jenkins-ecr-role"

String repositoryURI(String account_id, String aws_region, 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, String region) {
  account_ids.each { account ->
    target = repositoryURI(account, region, project_name)

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

    withAgentAWS(role: JENKINS_ROLE, roleAccount: account, region: region) {
      sh "\$(aws ecr get-login --region ${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 Nginx docker image') {
      steps {
        sshagent(credentials: ['git-aws-read-key']) {
          sh "docker build -t ${PACKAGE_REPO_LOCAL_REPO} --build-arg version=${NGINX_VERSION} ./nginx"
        }
      }
    }

    stage('Push docker images to dev ECR') {
      when {
        not { branch 'main' }
      }
      steps {
        pushImages(DEV_ACCOUNT_IDS, PACKAGE_REPO_LOCAL_REPO, 'docker-nginx', NGINX_VERSION, WEST_AWS_REGION)
      }
    }

    stage('Push docker images to prod ECRs') {
      when {
       branch 'main'
      }
      steps {
        pushImages(WEST_ACCOUNT_IDS, PACKAGE_REPO_LOCAL_REPO, 'docker-nginx', NGINX_VERSION, WEST_AWS_REGION)
        pushImages(EAST_ACCOUNT_IDS, PACKAGE_REPO_LOCAL_REPO, 'docker-nginx', NGINX_VERSION, EAST_AWS_REGION)
      }
    }
  }
}
