/*
* 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.plugin.jboss.helper.JBossHelper

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

final def isWindows = apTool.isWindows

def jbossPath = props['jbosspath']
def serverMode = props['serverMode']
def hostName = props['hostName']
def username = props['username'] != null ? props['username'] : ""
def password = props['password'] != null ? props['password'] : ""
def controllerPort = props['controllerPort']
def controllerHost = props['controllerHost']

println "The server mode is ${serverMode}"

def executable = isWindows ? "jboss-cli.bat" : "jboss-cli.sh"

def pathFile = new File(jbossPath)
def cliFile = new File(pathFile, executable)

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 = []

if (serverMode.equalsIgnoreCase("standalone")) {
    cmdArgs = [cliFile.absolutePath, "--connect"]

    if (controllerHost && controllerPort) {
        cmdArgs << "controller=${controllerHost}:${controllerPort}"
    }

    cmdArgs << "command=:shutdown"
}
else {
    println "Domain is the mode"
    cmdArgs = [cliFile.absolutePath, "--connect", "command=/host=${hostName}:shutdown"]
}

if (username) {
    cmdArgs << "--user=${username}"
}

if (password) {
    cmdArgs << "--password=${password}"
}

def helper = new JBossHelper(cmdArgs)
helper.runStopCommand("Stopping JBoss")

System.exit(0)
