/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Build
* IBM UrbanCode Deploy
* IBM UrbanCode Release
* IBM AnthillPro
* (c) Copyright IBM Corporation 2002, 2016. 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.websphereliberty.WebSphereLibertyHelper;
import com.urbancode.air.plugin.websphereliberty.WebSphereLibertyJMXHelper;

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

def props = apTool.getStepProperties();

def wlpHome = props['wlpHome'];
def wlpUserDir = props['wlpUserDir'];
def serverName = props['server'];
def serverHost = props['serverHost'].trim();
def controllerHostName = props['controllerHostName'].trim();
def controllerPort = props['controllerPort'].trim();
def adminUser = props['adminUser'].trim();
def adminPassword = props['adminPassword'].trim();
def trustStorePath = props['trustStorePath'].trim();
def trustStorePassword = props['trustStorePassword'].trim();

def status = true;
def serverList = serverName.tokenize(",");
def stoppedServers = [];
def alreadyStoppedServers = [];
def failedServers = [];

/* If collective controller hostname was specified we will try to stop the specified server via the controller and JMX */
if (controllerHostName?.trim()) {
    def jmxHelper = new WebSphereLibertyJMXHelper(adminUser, adminPassword, controllerHostName, controllerPort, trustStorePath, trustStorePassword);
    for (server in serverList) {
        server = server.trim();
        status = jmxHelper.stopServerViaController(wlpHome, server, serverHost);
        if (!status) {
            failedServers.add(server);
        }
    }
}
else {
    def wslh = new WebSphereLibertyHelper(wlpHome, wlpUserDir);
    if (serverList[0] == "ALL" || serverList[0].contains("*")) {
        def searchName = serverList[0];
        serverList = wslh.getServerNames(serverList[0]);
        if (serverList.length == 0) {
            throw new RuntimeException("No servers found matching ${searchName}");
        }
    }
    for (server in serverList) {
        server = server.trim();
        status = wslh.stopServer(server, apTool.isWindows);
        if (status == 0) {
            stoppedServers.add(server);
        }
        else if (status == 1) {
            alreadyStoppedServers.add(server);
        }
        else {
            failedServers.add(server);
        }
    }
}

apTool.setOutputProperty("stoppedServers", stoppedServers.join(","));
apTool.setOutputProperty("alreadyStoppedServers", alreadyStoppedServers.join(","));
apTool.setOutputProperty("failedServers", failedServers.join(","));
apTool.setOutputProperties();

if (failedServers.size() == 0) {
    System.exit(0)
}
else {
    System.exit(1)
}
