import com.urbancode.air.AirPluginTool;
import com.urbancode.air.CommandHelper;
import com.urbancode.air.plugin.jboss.helper.JBossHelper;
import java.io.File;

def apTool = new AirPluginTool(this.args[0], this.args[1]) //assuming that args[0] is input props file and args[1] is output props file
def props = apTool.getStepProperties();

def out = System.out
final def isWindows = apTool.isWindows;

def jbossPath = props['jbosspath'];
def appName = props['appName']
def allServerGroups = props['allServerGroups'] != null ? props['allServerGroups'].toBoolean() : false
def serverGroups = props['serverGroups'] != null ? props['serverGroups'] : "";
def controller = props['controller'] != null ? props['controller'] : "";
def cli = isWindows ? "jboss-cli.bat" : "jboss-cli.sh"

def pathFile = new File(jbossPath);
def cliFile = new File(pathFile, cli);

if (!cliFile.isFile()) {
    executable = isWindows ? "jboss-admin.bat" : "jboss-admin.sh"
    cliFile = new File(pathFile, executable)

    if (!cliFile.isFile()) {
        throw new Exception("Could not find JBoss executable")
    }
}

def cmdArgs = [cliFile.absolutePath];

if (!controller.equals("")) {
    cmdArgs << "--controller=${controller}"
    }

def scriptData = File.createTempFile('ud-jboss-', '.cli')
scriptData.deleteOnExit()

scriptData.write("");

scriptData.append("connect\n")
scriptData.append("deploy ");

scriptData.append(" --name=${appName}")

if (allServerGroups) {
    scriptData.append(" --all-server-groups")
}
else if (!serverGroups.equals("")) {
    scriptData.append(" --server-groups=${serverGroups}")
}

cmdArgs << "--file="+scriptData.absolutePath

def helper = new JBossHelper(cmdArgs);
helper.runDeployCommand("Enabling application on JBoss");

System.exit(0);
