/**
 * Licensed Materials - Property of IBM* and/or HCL**
 * UrbanCode Deploy
 * (c) Copyright IBM Corporation 2011, 2018. All Rights Reserved.
 * (c) Copyright HCL Technologies Ltd. 2018, 2019. All Rights Reserved.
 *
 * U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
 * GSA ADP Schedule Contract with IBM Corp.
 *
 * * Trademark of International Business Machines
 * ** Trademark of HCL Technologies Limited
 */

package com.urbancode.air.plugin.docker

import groovy.json.JsonSlurper
import com.urbancode.air.AirPluginTool
import com.urbancode.air.XTrustProvider
import com.urbancode.air.CommandHelper

public class AmazonECRClient {

    CommandHelper ch
    AirPluginTool apTool
    def accessKey
    def secretKey
    def ecsDockerUsername
    def ecsDockerPassword
    def imageName
    def region
    def awsCli
    def registry

    public AmazonECRClient(Properties props) {
        this.ch = new CommandHelper(new File('.'));
        this.accessKey = props['dockerRegistryUsername'].trim()
        this.secretKey = props['dockerRegistryPassword']
        this.imageName = props['dockerImageName'].trim()
        this.region = props['region'].trim()
        this.awsCli = props['awsCli'].trim() ?: "aws"
    }

    public def getDockerAuthToken (){
        def result
        def command = [awsCli, "--output", "json", "ecr", "get-authorization-token"]

        def raw = runCommandWithOutput("Authenticating with ECS", command)
        def authData = new JsonSlurper().parseText(raw).authorizationData[0]

        def decodedToken = new String(authData.authorizationToken.decodeBase64())
        result = decodedToken.replaceFirst("AWS:", "")
        registry = authData.proxyEndpoint.replaceFirst("https://", "")

        return result
    }

    public def getRegistry() {
        return registry
    }

    public def getTags() {

        def result
        def command = [awsCli, "ecr", "list-images"]
        command.addAll(["--repository-name", imageName])

        def outputText = runCommandWithOutput("Requesting images for repository, '${imageName}'", command)

        def images
        try {
            result = new JsonSlurper().parseText(outputText)?.imageIds
        }
        catch (Exception e){
            throw new RuntimeException("Unexpected output: ${outputText}", e)
        }

        return result
    }

    private def setCommandEnvironment() {

        ch.addEnvironmentVariable("AWS_ACCESS_KEY_ID", accessKey)
        ch.addEnvironmentVariable("AWS_SECRET_ACCESS_KEY", secretKey)

        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 runCommandWithOutput(String message, def command) {
        def result
        setCommandEnvironment()
        ch.runCommand(message, command, { proc ->
            proc.out.close() // close stdin
            proc.consumeProcessErrorStream(System.out) // forward stderr
            result = proc.text.trim();
        })

        return result
    }
}
