import groovy.transform.Field
import java.util.UUID

@Field
DEFAULT_REGISTRIES = [
    [accountId: '437795906767', region: 'us-east-1'],
    [accountId: '086679231553', region: 'us-east-1'],
    [accountId: '086679231553', region: 'us-east-2']
]

def call(Closure steps) {
    call([:], steps)
}

def call(Map args, Closure steps) {
    if (args.registries) {
        assert args.registries.getClass() in Collection: 'registries must be a list or set'
        args.registries.each { registry ->
            assert (registry['accountId'] && registry['region']): 'accountId and region are required for each registry'
        }
    }

    def registries = args.registries ?: DEFAULT_REGISTRIES

    // Override DOCKER_CONFIG to unique directory to ensure authentication is isolated from other jobs and other stages within the same job
    withEnv(["DOCKER_CONFIG=/tmp/jenkins/withEcr/${UUID.randomUUID().toString()}"]) {
        for (def registry in registries) {
            echo "Authenticating with ECR registry in account ID ${registry.accountId}, region ${registry.region}"
            sh "aws ecr get-login-password --region ${registry.region} | docker login --username AWS --password-stdin ${registry.accountId}.dkr.ecr.${registry.region}.amazonaws.com"
        }

        steps()
    }
}
