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']
def imInstallPath = props['IMInstallPath']
def versionName = props['VersionName']

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 cmdArgs = [imclExe.absolutePath,
                       "uninstall", versionName];
    ch.runCommand("Running imcl", cmdArgs);
    if (new File(wasInstallPath).exists()) {
        def ant = new AntBuilder();
        ant.delete(verbose: 'true', includeemptydirs: 'true') {
            fileset(dir:wasInstallPath, casesensitive: 'false', followsymlinks: 'false', defaultexcludes: 'false')
        }
    }
}
catch (Exception e) {
    println "Uninstalling WebSphere Application Server failed.";
    System.exit(1);;
}
