/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Build
* IBM UrbanCode Deploy
* IBM UrbanCode Release
* IBM AnthillPro
* (c) Copyright IBM Corporation 2002, 2013. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*/
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 File PLUGIN_HOME = new File(System.getenv().get("PLUGIN_HOME"))
def String getArch() {
    String result
    String arch = System.getProperty("os.arch").toLowerCase(Locale.US)

    if (arch.indexOf("amd64") > -1 || arch.indexOf("x64") > -1 || arch.indexOf("x86_64") > -1) {
        result = "x64"
    }
    else if (arch.indexOf("x86") > -1 || arch.indexOf("386") > -1 || arch.indexOf("486") > -1 ||
             arch.indexOf("586") > -1 || arch.indexOf("686") > -1 || arch.indexOf("pentium") > -1) {
        result = "x86"
    }
    else {
        result = "unknown"
    }
    return result
}

final def isWindows = apTool.isWindows

def jbossPath = props['jbosspath']
def startupMode = props['startupMode']
def serverConf = props['serverConf'].toString()
def timeout = props['timeout'].toInteger()
def hostName = props['hostName']
def portNumber = props['hostPort'].toInteger()

println "Starting JBoss in " + startupMode + " mode."
def executable

if (startupMode.equalsIgnoreCase("standalone")) {
    executable = isWindows ? "standalone.bat" : "standalone.sh"
}
else if (startupMode.equalsIgnoreCase("domain")) {
    executable = isWindows ? "domain.bat" : "domain.sh"
}
else {
    println "Startup Mode is a required value and cannot be 'none'"
    System.exit(1)
}

if (isWindows) {
    def arch = getArch()
    if (arch.equals("unknown")) {
        throw new Exception("Unable to initialize WinAPI, unknown architecture")
    }
    
    def libraryPath = new File(PLUGIN_HOME, "lib/native/${arch}/WinAPI.dll")
    System.setProperty("com.urbancode.winapi.WinAPI.dllPath", libraryPath.absolutePath)
 }

def pathFile = new File(jbossPath)
def cliFile = new File(pathFile, executable)
def cmdArgs = []

if (serverConf?.trim()?.size() == 0) {
    cmdArgs = [cliFile.absolutePath]
}
else {
    cmdArgs = [cliFile.absolutePath, "-c", serverConf]
}

def helper = new JBossHelper(cmdArgs)
helper.runStartCommand("Starting JBoss", timeout, hostName, portNumber)

System.exit(0)
