/*
 * 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.
 */
// Documentation: https://new-console.ng.bluemix.net/apidocs/48

import com.urbancode.air.AirPluginTool
import com.urbancode.air.ExitCodeException
import com.urbancode.air.plugins.autoscaler.AutoScaler
import com.urbancode.air.plugins.autoscaler.CloudFoundry
import com.urbancode.air.plugins.autoscaler.JSONHelper

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

final def workDir = new File('.').canonicalFile
def scalingApi    = props['scalingApi'].trim()
def app_id        = props['app_id'].trim()
def policy        = JSONHelper.getJSONText(props['policy'])

AutoScaler scale = new AutoScaler(scalingApi, app_id)

def policyId
try {
    policyId = scale.addPolicy(policy)
}
catch (ExitCodeException ex) {
    println "[Error] Could not successfully attach policy to application '${app_id}'."
    println ex
    System.exit(1)
}

if (!policyId) {
    System.exit(1)
}

println("[Ok] Successfully attached Policy '${policyId}' to Application '${app_id}'.")
// Set the policyId to a output property
apTool.setOutputProperty("policyId", policyId)
apTool.storeOutputProperties()