/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Build
* IBM UrbanCode Deploy
* IBM UrbanCode Release
* IBM AnthillPro
* (c) Copyright IBM Corporation 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.WebSphereLibertyServerXmlHelper;
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'];
def controllerPort = props['controllerPort'];
def adminUser = props['adminUser'];
def adminPassword = props['adminPassword'];
def keystorePassword = props['keystorePassword'];
def trustStorePath = props['trustStorePath'].trim();
def trustStorePassword = props['trustStorePassword'].trim();
def rpcUser = props['rpcUser'].trim();
def rpcUserPassword = props['rpcUserPassword'].trim();
def sshPrivateKey = props['sshPrivateKey'].trim();
def sshPrivateKeyPassword = props['sshPrivateKeyPassword'].trim();
def optionalArgs = props['optionalArgs'].trim();

def serverList = serverName.tokenize(",");

/* If the server hostname was specified we will try to join the specified server to the collective via the controller using JMX */
if (serverHost?.trim()) {
    def jmxHelper = new WebSphereLibertyJMXHelper(adminUser, adminPassword, controllerHostName, controllerPort, trustStorePath, trustStorePassword);

    /* Gather required authentication info. */
    def hostAuthInfo = [:]
    hostAuthInfo.put("rpcUser", rpcUser);
    if (rpcUserPassword?.trim()) {
        hostAuthInfo.put("rpcUserPassword", rpcUserPassword);
    }
    else {
        hostAuthInfo.put("sshPrivateKey", sshPrivateKey);
        if (sshPrivateKeyPassword?.trim()) {
            hostAuthInfo.put("sshPrivateKeyPassword", sshPrivateKeyPassword);
        }
    }

    for (server in serverList) {
        jmxHelper.joinCollectiveViaController(wlpHome, server.trim(), serverHost, keystorePassword, hostAuthInfo);
    }
}
else {
    def wslh = new WebSphereLibertyHelper(wlpHome, wlpUserDir);
    for (server in serverList) {
        server = server.trim();
        String configFileName = wslh.joinCollective(server, controllerHostName, controllerPort, adminUser, adminPassword, keystorePassword, optionalArgs, apTool.isWindows);

        // Update server.xml with include referencing configFileName
        def wslxh = new WebSphereLibertyServerXmlHelper(wlpHome, server, wlpUserDir);
        wslxh.appendIncludeInServerXml(configFileName);
    }
}
