/*
 * Licensed Materials - Property of IBM Corp.
 * IBM UrbanCode Deploy
 * (c) Copyright IBM Corporation 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.CommandHelper
import com.urbancode.air.plugin.cf.ic.helper.ResourceHelper
import com.urbancode.air.plugin.cf.ic.helper.CFICHelper

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

final def workDir = new File('.').canonicalFile

def ucdUser = apTool.getAuthTokenUsername()
def ucdPass = apTool.getAuthToken()
def ucdUri = new URI(System.getenv("AH_WEB_URL"))
def resourceHelper = new ResourceHelper(ucdUri, ucdUser, ucdPass)

def commandPath = props['commandPath']
CFICHelper icHelper = new CFICHelper(workDir, commandPath)

def rootPath = props['resourcePath']

def regFolderPath = rootPath + "/Registries"
def regFolderDescription = "All Bluemix registries for this API Endpoint."
def regFolder = resourceHelper.getOrCreateSubResource(regFolderPath, rootPath, "Registries", regFolderDescription)

def registryUrl = icHelper.getBluemixRegistryUrl()

def regName = "Bluemix Registry - ${registryUrl.replaceAll('/', '-')}"
def regPath = "${regFolderPath}/${regName}"
def regDescription = "Bluemix registry with url path '${registryUrl}."
def regResource = resourceHelper.getOrCreateSubResource(regPath, regFolderPath, regName, regDescription)

def regProperties = new HashMap<String, String>()
regProperties.put("dockerUrl", registryUrl)
regProperties.put("dockerUsername", registryUrl)
regProperties.put("dockerPassword", registryUrl)
def roleName = "BluemixRegistry"

resourceHelper.addRoleToResource(regResource, roleName, regProperties)

println("[OK] Configuration of Bluemix Registry has completed successfully.")