/*
* Licensed Materials - Property of IBM* and/or HCL**
* UrbanCode Deploy
* (c) Copyright IBM Corporation 2016, 2017. All Rights Reserved.
* (c) Copyright HCL Technologies Ltd. 2018. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*
* * Trademark of International Business Machines
* ** Trademark of HCL Technologies Limited
*/

import com.urbancode.air.AirPluginTool
import com.urbancode.air.plugin.odm.OdmHelper

// Get step properties
def apTool  = new AirPluginTool(args[0], args[1])
def inProps = apTool.getStepProperties()

String hostname = (inProps['hostname']!=null && inProps['hostname'].length()>0) ? inProps['hostname'].trim() : inProps['hostname']
String port     = inProps['port']
String username = (inProps['username']!=null && inProps['username'].length()>0) ? inProps['username'].trim() : inProps['username']
String password = inProps['password']

String resource  = (inProps['resource']!=null && inProps['resource'].length()>0) ? inProps['resource'].trim() : inProps['resource']
boolean addNew   = Boolean.valueOf(inProps['addNew'])
String propName  = inProps['propName']
String propValue = inProps['propValue']

String file           = inProps['file']
String merging        = inProps['merging']
String version        = inProps['version']
String ruleAppName    = inProps['ruleAppName']
String ruleAppVersion = inProps['ruleAppVersion']
String ruleSetName    = inProps['ruleSetName']
String ruleSetVersion = inProps['ruleSetVersion']

String tokenUrl = inProps['tokenUrl']
String scope = (inProps['scope']!=null && inProps['scope'].length()>0) ? inProps['scope'].trim() : inProps['scope']
String grantType = (inProps['grantType']!=null && inProps['grantType'].length()>0) ? inProps['grantType'].trim() : inProps['grantType']
String clientID = inProps['clientID']
String clientSecret = inProps['clientSecret']
String oAuthusername = inProps['oAuthusername']
String oAuthpassword = inProps['oAuthpassword']

while (hostname.endsWith('/')) {
    hostname = hostname.substring(0, hostname.length() - 1)
}

OdmHelper oh = new OdmHelper(username, password, tokenUrl, scope, grantType, clientID, clientSecret, oAuthusername, oAuthpassword)
String uri = "res/api/v1/ruleapps/" + resource + "/properties/" + propName

println ("[Action] Setting property ${propName}...")
if (!oh.setUri(hostname, port, uri)) {
    println ('[Error] Could not set URI.')
    System.exit(1)
}

def updated = oh.setProperty(propName, propValue, addNew)

if (updated) {
    println ("[Ok] Property '${propName}' set to '${propValue}'")
}
else {
    println ("[Error] Could not update property ${propName}")
    System.exit(1)
}