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 source = props['source'] != null ? props['source'] : ""
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 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}"
}

def helper = new JBossHelper(cmdArgs)

def scriptData = helper.createTempFile()

scriptData.withWriter { out ->
    out << "connect\n"
    out << "deploy "
    if (source?.trim()?.size() > 0) {
        def srcFile = new File(source)
        if (!srcFile.exists()) {
            throw new Exception("Applcation/jar path $source does not exist!")
        }
        out << "\"${srcFile.absolutePath}\""
    }
    out << " --name=${appName}"

    if (allServerGroups) {
        out << " --all-server-groups"
    }
    else if (serverGroups?.trim()?.size() > 0) {
        out << " --server-groups=${serverGroups}"
    }
}
cmdArgs << "--file=${scriptData.absolutePath}"

helper.runDeployCommand("Deploying Application/Jar to JBoss")

System.exit(0)
