/*
* Licensed Materials - Property of IBM* and/or HCL**
* UrbanCode Deploy
* (c) Copyright IBM Corporation 2002-2017. All Rights Reserved.
* (c) Copyright HCL Technologies Ltd. 2018. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*
* * Trademark of International Business Machines
* ** Trademark of HCL Technologies Limited
*/
import com.urbancode.air.AirPluginTool;
import com.urbancode.air.plugin.websphere.WebSphereCmdLineHelper;

final def isWindows = (System.getProperty('os.name') =~ /(?i)windows/).find()
out = System.out;

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

def cell = props['cell']
def server = props['server']
def commandPath = (props['commandPath']!=null?props['commandPath']:"");
def node = props['node']
def user = props['user']
def password = (props['password'] != null && props['password'] != "")? props['password'] : props['passScript']
def cluster = props['cluster']

def connType = props['connType']
def host = props['host'];
def port = props['port'];
def additionalArgs = props['additionalArgs'];
def appServerRootDir = props['appServerRootDir'];
def configRepoRootDir = props['configRepoRootDir'];
def fileName = props['fileName'];
def forServer = Boolean.valueOf(props['forServer']);
def propagate = Boolean.valueOf(props['propagate']);
def propKeyRing = Boolean.valueOf(props['propagateKeyRing']);
def deleteTempFileOnFailure = Boolean.valueOf(props['deleteTempFileOnFailure'])

File tempFile = File.createTempFile("temp", ".py", new File("."))
if (deleteTempFileOnFailure) {
    tempFile.deleteOnExit();
}

BufferedWriter temp = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempFile), "UTF-8"))
def current = "cell = AdminControl.getCell()";
temp.write(current, 0, current.length());
System.out.print(current)
current = "\npluginGen = AdminControl.completeObjectName('type=PluginCfgGenerator,*')";
temp.write(current, 0, current.length());
System.out.print(current)
String invokeArgs ="";
if (forServer && server?.trim()) {
    invokeArgs = appServerRootDir + " " + configRepoRootDir + " " + 
            "' + cell + ' " + node + " " + server + " "  + fileName + " " + propagate + " " + propKeyRing; 
}
else {
    invokeArgs = appServerRootDir + " " + configRepoRootDir + " " + 
            "' + cell + ' null null " + fileName;
}
String invokeCmd = "AdminControl.invoke(pluginGen,'generate', '" + invokeArgs + "')"; 
invokeCmd = "\n" + invokeCmd + "\n";
temp.write(invokeCmd, 0, invokeCmd.length());
System.out.print(invokeCmd);
temp.close();

def commandArgs = [commandPath + WebSphereCmdLineHelper.getWSADMINValue(), "-lang", "jython"];
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
}

if (wclh.isJythonUpgraded() == true) {
    commandArgs << "-usejython21";
    commandArgs << "true";
}

commandArgs << "-f";
commandArgs << tempFile.getName();

if (additionalArgs) {
    additionalArgs.split('\n').each { arg ->
        commandArgs << arg;
    }
}

println 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);
def exitVal = statusProc.exitValue()
if (exitVal == 0) {
    tempFile.delete();
}
System.exit(exitVal);
