import com.urbancode.air.CommandHelper;
import com.urbancode.air.AirPluginTool;

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

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 = PLUGIN_HOME + File.separator + "classes";

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";

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

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

cmdLineArgs << classpath;

// 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])

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