/*
 * Licensed Materials - Property of IBM Corp.
 * IBM UrbanCode Build
 * IBM UrbanCode Deploy
 * IBM UrbanCode Release
 * IBM AnthillPro
 * (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 java.util.Map;
import org.codehaus.jettison.json.JSONObject;
import org.codehaus.jettison.json.JSONArray;

import com.urbancode.air.AirPluginTool;

import groovy.io.FileType
import com.urbancode.ud.client.UDRestClient;
import com.urbancode.ud.client.ResourceClient;

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

def MAX_RETRIES = 3;

def weburl = System.getenv("AH_WEB_URL");
def user = apTool.getAuthTokenUsername();
def password = apTool.getAuthToken();
def finalURI = new URI(weburl);
def udClient = new ResourceClient(finalURI, user, password);

def registryHost = props['registryHost'];
def roleName = "ImageRegistry";

def getOrCreateSubResource = { resourcePath, parentUUID, description ->
    def resourceName = resourcePath.substring(resourcePath.lastIndexOf("/") + 1);
    def resource = null;
    def tries = 0;
    def done = false;
    while (!done && tries < MAX_RETRIES) {
        try {
            try {
                resource = udClient.getResourceByPath(resourcePath);
            }
            catch (IOException e) {
                //resource does not exist(i hope)
                resource = null;
            }
            if (resource == null) {
                def nodeId = udClient.createSubResource(parentUUID, resourceName, description);
                resource = udClient.getResourceByPath(resourcePath);
            }
            done = true;
        }
        catch (IOException e) {
            tries++;
            done = false;
            println("Got IOException in getOrCreateSubResource for ${resourcePath}");

            if (tries < MAX_RETRIES) {
                println ("Retrying...")
            }
            else {
                throw e;
            }
        }
    }

    return UUID.fromString(resource.getString("id"));
}

def addRoleToResource = { resource, role, properties ->
    def tries = 0;
    def done = false;
    while (!done && tries < MAX_RETRIES) {
        try {
            udClient.setRoleOnResource(resource.toString(), role, properties);
            done = true;
        } catch (IOException e) {
            tries++;
            done = false;
            println("Got IOException in addRoleToResource for ${resource}");
            if (tries < MAX_RETRIES) {
                println ("Retrying...")
            } else {
                throw e;
            }
        }
    }
}

def registryProps = new HashMap<String, String>();
registryProps.put("image.registry.host", registryHost);
registryProps.put("image.registry.user", props['registryUserName']);
registryProps.put("image.registry.password", props['registryPassword']);
registryProps.put("image.registry.email", props['registryEmail']);
registryProps.put("image.registry.allowInsecure", props['allowInsecure']);
registryProps.put("image.registry.type", props['registryType']);
registryProps.put("image.registry.icsApi", props['icsApi']);
registryProps.put("image.registry.icsSpace", props['icsSpace']);
registryProps.put("image.registry.icsOrg", props['icsOrg']);
registryProps.put("image.registry.icsApiKey", props['icsApiKey']);
registryProps.put("image.registry.cfHome", props['cfHome']);
registryProps.put("image.registry.awsRegion", props['awsRegion']);
registryProps.put("image.registry.awsCmdLineFile", props['awsCmdLineFile']);

def rootResource = udClient.getResourceByPath(props['parentResource']);
def rootResourceIdString = rootResource.getString("id");
def rootResourceId = UUID.fromString(rootResourceIdString);

def resourcePath = rootResource.path + "/" + roleName + " - " + registryHost;
def description = "Image registry resource for " + registryHost;
def registryResource = getOrCreateSubResource(resourcePath, rootResourceId, description);
addRoleToResource(registryResource, roleName, registryProps);

apTool.setOutputProperty("resourcePath", resourcePath);
apTool.setOutputProperties();
