/*
* Licensed Materials - Property of IBM* and/or HCL**
* UrbanCode Deploy
* (c) Copyright IBM Corporation 2013, 2017. All Rights Reserved.
* (c) Copyright HCL Technologies Ltd. 2018. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*
* * Trademark of International Business Machines
* ** Trademark of HCL Technologies Limited
*/
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 host = props['host'] ?: "localhost"
def mgmtPort = props['mgmtPort'] ?: "9999"
def additionalArgs = props['additionalArgs']

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 ")
scriptData.append(host)
scriptData.append(":")
scriptData.append(mgmtPort)
scriptData.append("\n")
scriptData.append("deploy ");

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

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

if (additionalArgs) {
    def arguments = additionalArgs.split('\n')

    for (def arg : arguments) {
        scriptData.append(" ${arg.trim()}")
    }
}

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

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

System.exit(0);
