/*
* 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 com.urbancode.air.plugin.automation.*;

//------------------------------------------------------------------------------
// GET ALL INPUT PARAMETERS
//------------------------------------------------------------------------------
final def workDir = new File('.').canonicalFile
final def javaHome = System.getenv('JAVA_HOME')
final def webUrl = System.getenv('WEB_URL')
final def authToken = System.getenv('AUTH_TOKEN')
final def buildLifeId = System.getenv('BUILD_LIFE_ID')
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 CommandHelper cmdHelper = new CommandHelper(workDir);

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'];
/*
def postURL = props['postURL'];
def postMessage = props['postMessage'];
*/

def jsonBody = "{\"application\": " + "\"$applicationName\"" + ", \"applicationProcess\":  " +"\"$appProcess\""+
    ", \"environment\": " +"\"$envName\""+ ", \"onlyChanged\": " +"\"$deployOnlyChanged\""+
    ", \"properties\": {},\"versions\": [{\"version\": " +"\"$versionName\""+ ", \"component\": " +
    "\"$compName\""+ " }]}" //,\"post-deploy-put-url\": " +"\"$postURL\""+ ", \"post-deploy-message\": " +"\"$postMessage\"}";


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

def cmdArgs = [javaFile.absolutePath, '-jar', udClientJarFile.absolutePath,
               "--weburl", url,
               "requestApplicationProcess",
               jsonFile,
               "--verbose"];

if (ucdAuthToken) {
    cmdArgs << "--authtoken" << ucdAuthToken
}
else {
    cmdArgs << "-username" << user << "-password" << password
}

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