/*
* 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 resource = inProps['resource'].trim()

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

def path = 'res/api/v1/'
String downloadName
if (resource.split('/').size() == 2) {    // XOM resource
    path += "xoms/${resource}/bytecode"
    downloadName = "${resource.split('/')[0]}"
}
else if (resource.split('/').size() == 4) {    // RuleSet archive
    path += "ruleapps/${resource}/archive"
    downloadName = "ruleApp_${resource.split('/')[0]}_${resource.split('/')[1]}.jar"
}
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)
}

OdmHelper oh = new OdmHelper(username, password)
if (!oh.setUri(hostname, port, path)) {
    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.")
    System.exit(0)
}
else {
    println ('[Error] Could not fetch resource.')
    System.exit(1)
}

