/*
* 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 java.io.*;
import java.util.*;
import com.urbancode.air.plugin.websphere.WebSphereCmdLineHelper;

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

final def workDir = new File('.').canonicalFile
final def props = new Properties();
final def inputPropsFile = new File(args[0]);
final def inputPropsStream = null;
try {
    inputPropsStream = new FileInputStream(inputPropsFile);
    props.load(inputPropsStream);
}
catch (IOException e) {
    throw new RuntimeException(e);
}

WebSphereCmdLineHelper wclh = new WebSphereCmdLineHelper(props);

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

def pluginHome = System.getenv("PLUGIN_HOME");
def scriptsDir = new File(new File(pluginHome), "jythonScripts");
def connType = props['connType']
def host = props['host'];
def port = props['port'];
def lang = "jython";
def scriptPath = new File(scriptsDir, "createSIBJMSConnectionFactory.jython").getCanonicalPath();

def commandArgs = [commandPath + WebSphereCmdLineHelper.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
}

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

commandArgs << "-f";
commandArgs << scriptPath;
commandArgs << args[0].replaceAll("\\\\", "\\\\\\\\");

println "Creating SIBJMSConnectionFactory with command : " + 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);
System.exit(statusProc.exitValue());
