import com.urbancode.air.CommandHelper;
final def workDir = new File('.').canonicalFile
final def ch = new CommandHelper(workDir);
final def props = new Properties();
final def inputPropsFile = new File(args[1]);
final def inputPropsStream = null;
try {
    inputPropsStream = new FileInputStream(inputPropsFile);
    props.load(inputPropsStream);
}
catch (IOException e) {
    throw new RuntimeException(e);
}

def cmdLineArgs = [];
def PLUGIN_HOME = System.getenv("PLUGIN_HOME");
def sysProps = props['sysProps'];
def path=props['path'];
def stepExe = args[0];
sysProps = sysProps.split('\n');

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 (File.separator == "\\") {
    // running on windows
    groovyExe += ".bat";
}

cmdLineArgs << groovyExe;
cmdLineArgs << "-cp";

if ( stepExe == "run_wldeploy.groovy" ) {
    cmdLineArgs << PLUGIN_HOME + File.separator + "classes";
    stepExe =  PLUGIN_HOME + File.separator + stepExe;
}
else {
    cmdLineArgs << PLUGIN_HOME + File.separator + "lib" + File.separator + "groovy-all-1.8.8.jar" +
            File.pathSeparator + path + File.pathSeparator +
            PLUGIN_HOME + File.separator + "classes";
    stepExe = PLUGIN_HOME + File.separator + "classes" + File.separator + stepExe + ".groovy";
}

sysProps.each { sysProp ->
    if (sysProp != null && sysProp.trim() != "") {
        cmdLineArgs << "-D" + sysProp;
    }
}

cmdLineArgs << stepExe;
cmdLineArgs << args[1];
cmdLineArgs << args[2];

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