/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Build
* (c) Copyright IBM Corporation 2012, 2014. 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.*
import org.codehaus.jettison.json.JSONArray
import org.codehaus.jettison.json.JSONObject

//------------------------------------------------------------------------------
// GET ALL INPUT PARAMETERS
//------------------------------------------------------------------------------
final def workDir = new File('.').canonicalFile
final def javaHome = System.getenv('JAVA_HOME')
final def pluginHome = System.getenv("PLUGIN_HOME");

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

final def javaFile = new File(new File(javaHome), 'bin/java' + (apTool.isWindows ? '.exe' : ''))
final def udClientJarFile = new File(new File(pluginHome), 'lib/udclient.jar')

def url = props['automation/url']
def user = props['automation/user']
def ucdAuthToken = props['automation/authToken']
def password = props['automation/passScript'] ?: props['automation/password']

def applicationName = props['applicationName']
def appProcess = props['applicationProcess']
def envName = props['environmentName']
def deployOnlyChanged = props['onlyChanged']
def compName = props['componentName']
def versionName = props['versionName']

JSONObject jsonBody = new JSONObject()
jsonBody.put("application", applicationName)
jsonBody.put("applicationProcess", appProcess)
jsonBody.put("environment", envName)
jsonBody.put("onlyChanged", deployOnlyChanged)
jsonBody.put("properties", new JSONObject().toString())

JSONArray versions = new JSONArray()
JSONObject version = new JSONObject()
version.put("version", versionName)
version.put("component", compName)
versions.put(version)

jsonBody.put("versions", versions)

def jsonFile = new File("deploy.json")
if (jsonFile.exists()) {
    jsonFile.delete()
}
jsonFile << jsonBody.toString()

UCDBase ucd = new UCDBase()
ucd.workDir = workDir
ucd.user = user
ucd.password = password
ucd.ucdAuthToken = ucdAuthToken
def command = [javaFile.absolutePath, '-jar', udClientJarFile.absolutePath,
               "--weburl", url,
               "requestApplicationProcess",
               jsonFile,
               "--verbose"]
ucd.addCredentials(command)

println "Executing deployment of application ${applicationName} to environment ${envName} using component ${compName}, version ${versionName}"
ucd.getCommandHelper().runCommand("Deploying application ${applicationName}", command);
println "Deployment started"
