/*
 * 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.plugin.jboss.helper.JBossHelper
import com.urbancode.air.AirPluginTool
import com.urbancode.commons.fileutils.filelister.FileListerBuilder
import com.urbancode.commons.fileutils.filelister.FileLister

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

final def isWindows = apTool.isWindows

def jbossPath = props['jbosspath']
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 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 baseCmdArgs = [cliFile.absolutePath]

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

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

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

def helper = new JBossHelper(baseCmdArgs)

def listFiles(def props) {
    def result = []
    def workDir = new File('.').canonicalFile
    def includes = props['includes']
    def excludes = props['excludes']
    FileListerBuilder flb = new FileListerBuilder(workDir)
    if (includes) {
        flb.include(includes.tokenize("\n") as String[])
    }
    if (excludes) {
        flb.exclude(excludes.tokenize("\n") as String[])
    }
    FileLister fl = flb.build()
    def unparsedList = fl.list()
    for (typedFile in unparsedList) {
        def newFile = new File(typedFile.path())
        if (newFile.isFile()) {
            println "found ${typedFile.path()}"
            result << newFile
        }
    }
    return result
}
def fileList = listFiles(props)
println "Deploying " + fileList.size() + " files"

for (srcFile in fileList) {
    def appName = props['appName']
    def runName = props['runName']
    def scriptData = helper.createTempFile()
    def cmdArgs = baseCmdArgs
    scriptData.withWriter { out ->
        out << "connect "
        out << host
        out << ":"
        out << mgmtPort
        out << "\n"
        out << "deploy "
        out << "\"${srcFile.absolutePath}\""
        if (!appName) {
            appName = srcFile.getName()
        }
        out << " --name=${appName}"

        if (runName) {
            out << " --runtime-name=${runName}"
        }
        else {
            out << " --runtime-name=${srcFile.getName()}"
        }

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

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

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

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

System.exit(0)
