/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Deploy
* (c) Copyright IBM Corporation 2017. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*/

import groovy.json.JsonSlurper
import com.urbancode.air.AirPluginTool
import com.urbancode.air.CommandHelper
import com.urbancode.air.plugin.docker.DockerHelper

def apTool = new AirPluginTool(this.args[0], this.args[1])
def props = apTool.getStepProperties()

String awsCli = props["awsCli"].trim()
String region = props["region"].trim()

// If AWS CLI is set, use AWS authentication
if (awsCli) {

    def command = [awsCli, "--output", "json", "ecr", "get-authorization-token"]

    CommandHelper ch = new CommandHelper(new File("."))
    ch.addEnvironmentVariable("AWS_ACCESS_KEY_ID", props["dockerRegistryUserName"])
    ch.addEnvironmentVariable("AWS_SECRET_ACCESS_KEY", props["dockerRegistryUserPassword"])

    if (!region) {
        def defaultRegion = System.getenv("AWS_DEFAULT_REGION")

        if (!defaultRegion) {
            region = "us-east-1"
            println "Could not find environment variable AWS_DEFAULT_REGION. Setting to '${region}'"
        }
        else {
            region = defaultRegion
            println "Setting region to '${region}' based on environment variable, AWS_DEFAULT_REGION"
        }
    }

    ch.addEnvironmentVariable("AWS_DEFAULT_REGION", region)

    def raw
    ch.runCommand("Authenticating with ECS", command, { proc ->
        proc.out.close() // close stdin
        proc.consumeProcessErrorStream(System.out) // forward stderr
        raw = proc.text.trim();
    })
    def authData = new JsonSlurper().parseText(raw).authorizationData[0]
    def decodedToken = new String(authData.authorizationToken.decodeBase64())

    props["dockerRegistryUserName"]     = new String("AWS")
    props["dockerRegistryUserPassword"] = new String(decodedToken.replaceFirst("AWS:", ""))
}


def helper = new DockerHelper(apTool)
helper.runDockerCommand("login", props)

apTool.storeOutputProperties()
