import java.io.*;
import java.util.*;
import com.urbancode.air.CommandHelper;
import com.urbancode.air.AirPluginTool;

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

def wasInstallPath = props['WASInstallPath'].trim();
def imInstallPath = props['IMInstallPath'].trim();
def imRepository = props['IMRepository'].trim();
def imShared = props['IMShared'].trim();
def versionName = props['VersionName'].trim();
def javaIMRepository = props['JavaIMRepository'].trim();
def javaVersionName = props['JavaVersionName'].trim();
def additionalArgs = props['additionalArgs'].trim();

if (javaIMRepository != "" && !javaIMRepository.equalsIgnoreCase(imRepository)) {
  imRepository = imRepository + "," + javaIMRepository;
}

try {
    while (imInstallPath.endsWith(File.separator)) {
        imInstallPath = imInstallPath.substring(0, imInstallPath.length()-1);
    }
    def toolsDir = new File(imInstallPath, "eclipse/tools");
    def imclExe = new File(toolsDir, "imcl");
    if (isWindows) {
        imclExe = new File(toolsDir, "imcl.bat");
        if (!imclExe.isFile()) {
            imclExe = new File(toolsDir, "imcl.exe");
        }
    }

    if (!imclExe.isFile()) {
        throw new Exception("Could not find imcl executable in ${toolsDir.absolutePath}");
    }

    def ch = new CommandHelper(toolsDir);
    def cmArgs = [];
    if (javaVersionName != "") {
        cmdArgs = [imclExe.absolutePath,
                       "install", versionName, javaVersionName,
                       "-repositories", imRepository,
                       "-installationDirectory", wasInstallPath,
                       "-acceptLicense",
                       "-showVerboseProgress"];
    }
    else {
        cmdArgs = [imclExe.absolutePath,
                       "install", versionName,
                       "-repositories", imRepository,
                       "-installationDirectory", wasInstallPath,
                       "-acceptLicense",
                       "-showVerboseProgress"];
    }

    if (imShared?.trim()) {
        cmdArgs << "-sharedResourcesDirectory";
        cmdArgs << imShared.trim();
    }

    if (additionalArgs) {
        additionalArgs.split('\n').each { arg ->
            cmdArgs << arg;
        }
    }

    ch.runCommand("Running imcl", cmdArgs);
}
catch (Exception e) {
    println "Installing WebSphere Application Server failed.";
    System.exit(1);;
}
