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

import com.urbancode.air.AirPluginTool
import com.urbancode.air.plugin.docker.AmazonECRClient
import com.urbancode.air.plugin.docker.ArtifactoryClient
import com.urbancode.air.plugin.docker.ICSClient
import com.urbancode.air.plugin.docker.RegistryClient
import com.urbancode.ud.client.ComponentClient
import com.urbancode.ud.client.VersionClient

final String VERSION_DOCKER_IMAGE_TAG = "dockerImageTag"; // Docker tag, like "latest"
final String VERSION_DOCKER_IMAGE_ID  = "dockerImageId";  // Docker id, 64 character check sum for the ID - soon to be deprecated in favor of signature
final String IMAGE_SIGNATURE = "dockerImageSignature";

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

if (props['dockerRegistryName'] == null || props['dockerRegistryName'].size() == 0) {
    props['dockerRegistryName'] = 'index.docker.io'
}
String registry         = props['dockerRegistryName'].trim()
String componentName    = props['componentName'].trim()
String namingConvention = props['namingConvention']?:"hyphenated"
String registryType     = props['registryType']

String ucdUsername = "PasswordIsAuthToken"
String ucdPassword = String.format("{\"token\": \"%s\"}", System.getenv("AUTH_TOKEN"))
URI webUrl = new URI(System.getenv("AH_WEB_URL"))

def awsTags
try {
    def client
    // ICS
    if (registryType.equals('true')) {
        client = new ICSClient(props)
    }
    // Artifactory
    else if (registryType.equals('artifactory')){
        client = new ArtifactoryClient(props)
    }
    // Amazon ECR
    else if (registryType.equals('amazon')){
        def awsClient = new AmazonECRClient(props)
        props['username'] = "AWS" //get from aws command instead
        props['password'] = awsClient.getDockerAuthToken()
        props['dockerRegistryName'] = awsClient.getRegistry()
        println "Found Docker registry: ${props['dockerRegistryName']}"
        awsTags = awsClient.getTags()
    }
    // Docker
    else {
        client = new RegistryClient(props)
    }

    Map tagIdLabels = [:]
    if (registryType.equals('amazon')) {
        awsTags.each { tagIdLabels.put(it.imageTag, it.imageDigest) }
    } else {
        ArrayList tags = client.getTags()
        tags.each { tag ->
            String id = client.getIdForTag(tag)
            Map<String,String> labels = new HashMap<String,String>()
            labels.putAll(client.getLabelsForTag(tag) ?: new HashMap<String,String>())
            if (id) {
                tagIdLabels.put(tag, [id, labels])
            }
        }
    }

    ComponentClient componentClient = new ComponentClient(webUrl, ucdUsername, ucdPassword);
    VersionClient versionClient;

    List<String> existingVersions = componentClient.getComponentVersions(componentName, true);

    tagIdLabels.each {
        String tag = it.key
        def id     = it.value
        String shortId
        HashMap<String, String> labels
        // For Amazon ECR
        if (id.contains(":")) {
            shortId = id.split(":")[1].substring(0,7)
        }
        // For all else
        else {
            id = it.value[0]
            // IBM Container Services
            if (id.contains(":")) {
                shortId = id.split(":")[1].substring(0,7)
            // For Docker and Artifactory
            } else {
                shortId = id.substring(0,7)
            }
            labels  = it.value[1]
        }
        String versionName

        switch (namingConvention) {
            case "hyphenated":
                versionName = tag + " - " + shortId
                break
            case "space":
                versionName = tag + " " + shortId
                break
            case "tag_only":
                versionName = tag
                break
        }
        if (!existingVersions.contains(versionName)) {
            versionClient = new VersionClient(webUrl, ucdUsername, ucdPassword);
            println "[Action] Creating new version, ${versionName}"
            String versionId = versionClient.createVersion(componentName, versionName, "Imported from ${registry}")
            apTool.setOutputProperty("VersionID", versionId);
            versionClient.setVersionProperty(versionName, componentName, VERSION_DOCKER_IMAGE_TAG, tag, false)
            if (registryType.equals('amazon')) {
                versionClient.setVersionProperty(versionName, componentName, IMAGE_SIGNATURE, id, false)
            } else {
                versionClient.setVersionProperty(versionName, componentName, VERSION_DOCKER_IMAGE_ID, id, false)
                labels.each { key, value ->
                    println "[Action] Adding property ${key}=${value} for version ${versionName}"
                    versionClient.setVersionProperty(versionName, componentName, key, value, false)
                }
            }
            versionClient.client.close();
        }
        else {
            println "[Ok] Version, '${versionName}' already exists. Skipping..."
        }
    }
}
finally {
    apTool.storeOutputProperties();
}

println "[Ok] Import Complete"
