/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Deploy
* (c) Copyright IBM Corporation 2016, 2017. 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 resource = inProps['resource'].trim()

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

String[] resourceArray = resource.split('/')
String path = "res/apiauth/v1/ruleapps/${resource}"
String downloadName
def versionNumber
OdmHelper oh = new OdmHelper(username, password)

//If no version specified, get highest
if (resourceArray.size() == 1 || resourceArray.size() == 3) {
    String highestVersionPath = path + "/highest"
    if (!oh.setUri(hostname, port, highestVersionPath)) {
        println ('[Error] Could not set URI.')
        System.exit(1)
    }
    versionNumber = oh.getHighestVersion()
    if (versionNumber){
        path += "/${versionNumber}" // add latest version number to base path
        downloadName = "ruleApp_${resourceArray[0]}_${versionNumber}.jar"
    }
    else {
        println ("[Error] Not able to determine highest version for resource: ${resource}")
        println ('[Possible Solution] Please update resource with a valid value and proper formatting')
        System.exit(1)
    }
}
//If version is specified
else if (resourceArray.size() == 2 || resourceArray.size() == 4) {    // RuleApp resource
    downloadName = "ruleApp_${resourceArray[0]}_${resourceArray[1]}.jar"
}
//If formatting is wrong overall
else {
    println ('[Error] Resource format invalid.')
    println ('[Possible Solution] Please update the step configuration with a valid resource definition supplied in the ' +
             'Resource property description.')
    System.exit(1)
}

String archivePath = path + "/archive"
if (!oh.setUri(hostname, port, archivePath)) {
    println ('[Error] Could not set URI.')
    System.exit(1)
}
println ('[Action] Fetching Resource...')
def deployed = oh.fetchResource(workDir, downloadName)
if (deployed) {
    println ("[Ok] Resource fetched.")
}
else {
    println ('[Error] Could not fetch resource.')
    System.exit(1)
}

//Get properties associated with resource
String propsPath = path + "/properties"

println ('[Action] Setting Resource properties as step output properties...')
if (!oh.setUri(hostname, port, propsPath)) {
    println ('[Error] Could not set URI.')
    System.exit(1)
}
def ruleProps = oh.getProperties()
if (ruleProps.size() > 0) {
    for (props in ruleProps) {
        println ('[Info] Property found: ' + props.id.toString())
        apTool.setOutputProperty(props.id.toString(), props.value.toString())
    }
    apTool.storeOutputProperties()
    println ("[Ok] Properties set.")
}
else if (ruleProps.size() == 0) {
    println ('[Info] No properties found for resource')
}
else {
    println ('[Error] Could not set output properties.')
    System.exit(1)
}

