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

    def serverGroupList = serverGroups.split(",")

    for (def serverGroup in serverGroupList) {
        out << "/server-group=${serverGroup}:restart-servers"
        out << "\n"
    }

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

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

helper.runRestartServerGroupsCommand("Restarting JBoss Server Groups", timeout);

System.exit(0);