/*
* 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 cli = isWindows ? "jboss-cli.bat" : "jboss-cli.sh"
def jbossPath = props['jbosspath']
def controller = props['controller'] != null ? props['controller'] : ""
def timeout = props['timeout'] != "" ? props['timeout'].toInteger() : null
def username = props['username'] != null ? props['username'] : ""
def password = props['password'] != null ? props['password'] : ""
def host = props['host'] ?: "localhost"
def mgmtPort = props['mgmtPort'] ?: "9999"
String domainHostname = props['domainHostname'].trim()
String serverInstance = props['serverInstance'].trim()
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 FileNotFoundException("Could not find JBoss executable.")
    }
}

def cmdArgs = [cliFile.absolutePath]

if (controller?.trim()?.size() > 0) {
    cmdArgs << "--controller=${controller}"
}

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

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

def helper = new JBossHelper(cmdArgs)

def scriptData = helper.createTempFile()

// /host=master/server-config=udeployTest1:restart

scriptData.withWriter { out ->
    out << "connect "
    out << host
    out << ":"
    out << mgmtPort
    out << "\n"
    if (domainHostname) {
        URL domainUrl = new URI('https', domainHostname, null, null).toURL()
        out << "/host=${domainUrl.getHost()}"
    }
    if (serverInstance) {
        out << "/server-config=${serverInstance}"
    }
    out << ":restart"

    if (additionalArgs) {
        def arguments = additionalArgs.split('\n')
        for (def arg : arguments) {
            out << " ${arg.trim()}"
        }
    }
}
helper.printScriptContents(scriptData)

cmdArgs << "--file=${scriptData.absolutePath}"

helper.runRestartServerCommand("Restarting JBoss Server Instance: " + serverInstance, timeout);

System.exit(0);
