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 profileTemplatePath = props['ProfileTemplatePath'].trim();
def wasProfileName      = props['WASProfileName'].trim();
def wasProfilePath      = props['WASProfilePath'].trim();
def wasAdminUsername    = props['WASAdminUsername'].trim();
def wasAdminPassword    = props['WASAdminPassword'].trim();

def wasCellName         = props['WASCellName'].trim();
def wasNodeName         = props['WASNodeName'].trim();
def wasHostName         = props['WASHostName'].trim();
def wasPortsFile        = props ['WASPortsFile'].trim();
def additionalArgs      = props['additionalArgs'].trim();


try {
    while (wasInstallPath.endsWith(File.separator)) {
        wasInstallPath = wasInstallPath.substring(0, wasInstallPath.length()-1);
    }
    def manageProfilesName = "manageprofiles."+(isWindows?"bat":"sh");
    def binDir             = new File(wasInstallPath, "bin");
    def manageProfilesExe  = new File(binDir, manageProfilesName);
    def ch                 = new CommandHelper(binDir);
    def cmdArgs            = [manageProfilesExe.absolutePath,
                               "-create",
                               "-templatePath", profileTemplatePath,
                               "-profileName", wasProfileName,
                               "-profilePath", wasProfilePath,
                               "-enableAdminSecurity", "true",
                               "-adminUserName", wasAdminUsername,
                               "-adminPassword", wasAdminPassword];

    if (wasPortsFile?.trim()) {
        cmdArgs << "-portsFile";
        cmdArgs << wasPortsFile.trim();
    }
    if (wasCellName?.trim()) {
        cmdArgs << "-cellName";
        cmdArgs << wasCellName.trim();
    }
    if (wasNodeName?.trim()) {
        cmdArgs << "-nodeName";
        cmdArgs << wasNodeName.trim();
    }
    if (wasHostName?.trim()) {
        cmdArgs << "-hostName";
        cmdArgs << wasHostName.trim();
    }
    if (additionalArgs) {
        additionalArgs.split('\n').each { arg ->
            cmdArgs << arg;
        }
    }

    ch.runCommand("Running manageprofiles", cmdArgs);
}
catch (Exception e) {
    println "Creating a profile failed.";
    System.exit(1);;
}
