/*
* 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.
*/
package com.urbancode.air.plugin.websphere;

import java.util.Collection;

public class WebSphereCmdLineHelper {
    static private final String wsant;
    static private final String wsadmin;
    static {
        wsant = "ws_ant.sh";
        wsadmin = "wsadmin.sh";
        def isWindows = (System.getProperty('os.name') =~ /(?i)windows/).find()
        def isOS400 = (System.getProperty('os.name') =~ /(?i)os\/400/).find()
        if (isWindows) {
           wsant = "ws_ant.bat"
           wsadmin = "wsadmin.bat"
        }
        if (isOS400) {
           wsant = "ws_ant"
           wsadmin = "wsadmin"
        }
    }
    
    //------------------------------------------------------------------------------------------------------------------
    static public String getWSADMINValue() {
        return wsadmin;
    }
    
    static public String getWSANTValue() {
        return wsant;
    }

    def commandPath;
    def user;
    def password;
    def pluginHome = new File(System.getenv("PLUGIN_HOME"));
    def scriptsDir = new File(pluginHome, "jythonScripts");
    def connType;
    def host;
    def port;
    def clusterName;
    def additionalArgs;
    def lang = "jython";
    def isWindows = (System.getProperty('os.name') =~ /(?i)windows/).find()
    def out = System.out;

    public WebSphereCmdLineHelper(def props) {
        commandPath = props['commandPath'];
        user = props['user'];
        password = (props['password'] != null && props['password'] != "")? props['password'] : props['passScript'];
        connType = props['connType'];
        host = props['host'];
        port = props['port'];
        lang = (props['lang'] != null && props['lang'] != "")? props['lang'] : "jython";
        additionalArgs = props['additionalArgs'];
    }

    public boolean isJythonUpgraded() {
        def jythonUpgrade = false;
        def cmdArgs = [commandPath + getWSADMINValue(), "-h", "jython"];

        println "Running Check to see if jython was upgraded";
        println cmdArgs.join(" ");

        Process proc = cmdArgs.execute();
        proc.out.close();
        OutputStream oStream = new ByteArrayOutputStream();
        OutputStream eStream = new ByteArrayOutputStream();
        proc.waitForProcessOutput(oStream, eStream);
        String output = oStream.toString();
        int usejython21 = output.indexOf("usejython21");
        if (usejython21 != -1) {
            jythonUpgrade = true;
        }

        return jythonUpgrade;
    }

    public void runWSAdminScript(def scriptPath, String msg, String... arguments) {
        runWSAdminScript(scriptPath, msg, null, arguments);
    }

    public void runWSAdminScript(def scriptPath, String msg, Closure exitCodeChecker, String... arguments) {
        def commandArgs = [commandPath + getWSADMINValue(), "-lang", lang];
        commandArgs << "-conntype"
        commandArgs << connType.trim();
        
        if (host) {
            commandArgs << "-host";
            commandArgs << host;
        }

        if (port) {
            commandArgs << "-port";
            commandArgs << port;
        }

        if (user) {
            commandArgs << "-user"
            commandArgs <<  user
            commandArgs << "-password"
            commandArgs << password
        }

        /* Check if running on WAS9, need to use Jython 2.1 */
        if (isJythonUpgraded() == true) {
            commandArgs << "-usejython21";
            commandArgs << "true";
        }

        additionalArgs?.split("\n")?.each { arg ->
            def value = arg?.trim();
            if (value != null && value != "") {
                commandArgs << value;
            }
        }

        commandArgs << "-f";
        commandArgs << scriptPath;
        arguments.each { arg ->
            commandArgs << arg;
        }

        println msg + " : " + commandArgs.join(' ');
        def procBuilder = new ProcessBuilder(commandArgs);

        if (isWindows) {
            def envMap = procBuilder.environment();
            envMap.put("PROFILE_CONFIG_ACTION","true");
        }

        def statusProc = procBuilder.start();
        def outPrint = new PrintStream(out, true);
        statusProc.waitForProcessOutput(outPrint, outPrint);
        if (exitCodeChecker == null) {
            System.exit(statusProc.exitValue());
        }
        else {
            exitCodeChecker(statusProc.exitValue());
        }
    }

    public void runWSAntScript(def scriptPath, def taskName, String msg, Closure exitCodeChecker, String... arguments) {
        def commandArgs = [commandPath + getWSANTValue(), "-f", scriptPath, taskName];
        println msg + " : " + commandArgs.join(' ');
        def procBuilder = new ProcessBuilder(commandArgs);
        def statusProc = procBuilder.start();
        def outPrint = new PrintStream(out, true);
        statusProc.waitForProcessOutput(outPrint, outPrint);
        if (exitCodeChecker == null) {
            System.exit(statusProc.exitValue());
        }
        else {
            exitCodeChecker(statusProc.exitValue());
        }
    }
}
