/*
 * Licensed Materials - Property of IBM Corp.
 * IBM UrbanCode Deploy
 * (c) Copyright IBM Corporation 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.CommandHelper

final def workDir = new File('.').canonicalFile
final def apTool = new AirPluginTool(args[1], args[2])
final def props = apTool.getStepProperties()
final def isWindows = apTool.isWindows

CommandHelper ch = new CommandHelper(workDir)
def cmdLineArgs = []
def PLUGIN_HOME = System.getenv("PLUGIN_HOME")
def sysProps = props['sysProps']
def jarPath= props['path']
def stepExe = PLUGIN_HOME + File.separator + args[0]
def classpath = new StringBuilder(PLUGIN_HOME + File.separator + "classes")
final def PLUGIN_LIB = PLUGIN_HOME + File.separator + "lib"

def JAVA_HOME = System.getenv("JAVA_HOME")
// if a different JAVA_HOME is set by user, use that instead.
if(props['javahome']) {
    JAVA_HOME = props['javahome']
}
ch.addEnvironmentVariable("JAVA_HOME", JAVA_HOME)

// Get GROOVY_HOME from the currently running groovy instance
// If we're impersonating then we might fail to get the ENV variable.
def groovyHome = System.getProperty("groovy.home")
def groovyExe = groovyHome + File.separator + "bin" + File.separator + "groovy"

if (isWindows) {
    groovyExe += ".bat"
}

cmdLineArgs << groovyExe
cmdLineArgs << "-cp"

classpath.append(File.pathSeparator + PLUGIN_LIB + File.separator + "jettison-1.1.jar")
classpath.append(File.pathSeparator + PLUGIN_LIB + File.separator + "CommonsUtil.jar")
classpath.append(File.pathSeparator + PLUGIN_LIB + File.separator + "securedata.jar")
classpath.append(File.pathSeparator + PLUGIN_LIB + File.separator + "commons-codec.jar")

if (args[0] == "discover_wl.groovy") {
    classpath.append(File.pathSeparator + PLUGIN_LIB + File.separator +"uDeployRestClient.jar")
    classpath.append(File.pathSeparator + PLUGIN_LIB + File.separator + "commons-io.jar")
}
else  if (args[0] != "run_wldeploy.groovy") {
    // append weblogic jar for scripts that require it
    classpath.append(File.pathSeparator + jarPath + File.pathSeparator + PLUGIN_LIB + File.separator + "groovy-all-1.8.8.jar")

    if (args[0] == "configure_wl.groovy") {
        classpath.append(File.pathSeparator + PLUGIN_LIB + File.separator +"uDeployRestClient.jar")
    }
}

if (isWindows) {
    cmdLineArgs << '"' + classpath.toString() + '"'
}
else {
    cmdLineArgs << classpath.toString()
}

// append user defined java system properties
if (sysProps) {
    sysProps = sysProps.split('\n')
}
sysProps.each {sysProp ->
    if (sysProp != null && sysProp.trim() != "") {
        cmdLineArgs << "-D" + sysProp
    }
}

cmdLineArgs.addAll(stepExe, args[1], args[2])

if(apTool.getEncKey() != null) {
    ch.addEnvironmentVariable("UCD_SECRET_VAR", apTool.getEncKey())
}

ch.runCommand(cmdLineArgs.join(' '), cmdLineArgs)