/**
 * Licensed Materials - Property of IBM Corp.
 * IBM UrbanCode Deploy
 * (c) Copyright IBM Corporation 2011, 2016. 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.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

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']
String componentName    = props['componentName']
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"))


try {
    def client
    if (registryType.equals('true')) {
        client = new ICSClient(props)
    }
    else {
        client = new RegistryClient(props)
    }

    ArrayList tags = client.getTags()
    Map tagIdLabels = [:]
    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
        String id      = it.value[0]
        String shortId = id.substring(0,7)
        HashMap<String, String> 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)
            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"
