/*
* 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.plugin.odm.OdmHelper

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

String hostname = inProps['hostname'].trim()
String port     = inProps['port'].trim()
String username = inProps['username']
String password = inProps['password']

String file           = inProps['file'].trim()
String merging        = inProps['merging'].trim()
String version        = inProps['version'].trim()
String ruleAppName    = inProps['ruleAppName'].trim()
String ruleAppVersion = inProps['ruleAppVersion'].trim()
String ruleSetName    = inProps['ruleSetName'].trim()
String ruleSetVersion = inProps['ruleSetVersion'].trim()


if ((merging.equals('NONE') && !version.equals('NONE')) || (!merging.equals('NONE') && version.equals('NONE'))) {
    println ('[Error] If using automatic version policies, neither Merging Policy or Versioning policy can be NONE.')
    println ('[Possible Solution] Either select a value (other than NONE) for both Merging Policy and Versioning Policy ' +
             'or leave both as NONE and explictly specify the RuleApp Name, RuleApp Version, RuleSet Name, and RuleSet Version.')
    System.exit(1)
}

OdmHelper oh = new OdmHelper(username, password)
def ruleType
if (merging.equals('NONE') && version.equals('NONE')) {
    ruleType = "RuleSet"
    if (!oh.setUri(hostname, port, "res/apiauth/v1/ruleapps/${ruleAppName}/${ruleAppVersion}/${ruleSetName}/${ruleSetVersion}")) {
        println ('[Error] Could not set URI.')
        System.exit(1)
    }

}
else {
    ruleType = "RuleApp"
    if (!oh.setUri(hostname, port, "res/apiauth/v1/ruleapps?merging=${merging}&version=${version}")) {
        println ('[Error] Could not set URI.')
        System.exit(1)
    }
}
println ("[Action] Deploying ${ruleType} archive...")
def deployed = oh.deployFile(file, "${ruleType} Archive", "${ruleType} archive")
if (deployed) {
    println ("[Ok] ${ruleType} Archive deployed.")
    System.exit(0)
}
else {
    println ("[Error] Could not deploy ${ruleType} Archive.")
    System.exit(1)
}