/*
* 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 name = props['name']
def entries = props['entries']
def connector = props['connector'].split(",") as List
def profile = props['profile']
def cli = isWindows ? "jboss-cli.bat" : "jboss-cli.sh"
def controller = props['controller'] != null ? props['controller'] : ""
def username = props['username'] != null ? props['username'] : ""
def password = props['password'] != null ? props['password'] : ""
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?.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()

scriptData.withWriter { out ->
    out << "connect "
    out << host
    out << ":"
    out << mgmtPort
    out << "\n"
    out  << "connection-factory add --name=${name} --entries=${entries} --connector={\"${connector[0]}\"=>"

    if (connector.size() > 1) {
        def connectCount = 0
        out  << "["
        for (connection in connector) {
            out  << "\"${connection}\""
            connectCount++
            if (connectCount < connector.size()) {
                out  << ","
            }
        }
        out  << "]"
    }
    else {
        out  << "undefined"
    }

    out  << "}"

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

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

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

helper.runFactoryCommand("Adding factory to JBoss")

System.exit(0)
