/*
* 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.websphere.WebSphereCmdLineHelper;

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

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 soapTimeout = props['soapTimeout'];
def deleteTempFileOnFailure = Boolean.valueOf(props['deleteTempFileOnFailure']);

File tempFile = File.createTempFile("temp", ".py", new File("."))
File soapSettingTempFile = File.createTempFile("wsadmin_soap_props", null, workDir)
File soapRedirectSettingTempFile = File.createTempFile("wsadmin_soap_redirect_props", null, workDir)
BufferedWriter temp = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempFile), "UTF-8"))

if (deleteTempFileOnFailure) {
    soapSettingTempFile.deleteOnExit();
    soapRedirectSettingTempFile.deleteOnExit();
    tempFile.deleteOnExit();
}

if (server == null || server.startsWith('${p:') || server.trim() == "") {
  invoke = "AdminControl.invoke(AdminControl.queryNames('type=Cluster,name=" + cluster + ",*'), 'start', '')"
} else {
    if (node && node.trim().length() > 0) {
      invoke = "AdminControl.startServer('"+ server + "', '" + node + "')"
    }
    else {
      invoke = "AdminControl.startServer('"+ server + "')"
    }
}
temp.write(invoke, 0 , invoke.length())
System.out.println invoke
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";
}

if ('SOAP' == connType.trim() && soapTimeout && soapTimeout.trim().length() > 0) {
    try {
        soapTimeout.toInteger()
        // try to find the soap client properties file
        def soapPropFileDir = new File(new File(commandPath).parentFile, 'properties')
        def soapPropFile = new File(soapPropFileDir, 'soap.client.props')
        Properties soapProps = new Properties()
        if (soapPropFile.exists()) {
            soapPropFile.withInputStream { soapProps.load(it)}
        }
        else {
            println "Warning: could not locate soap.client.properties file in $soapPropFileDir"
        }

        soapProps['com.ibm.SOAP.requestTimeout'] = soapTimeout

        soapSettingTempFile.withOutputStream {
            soapProps.save(it, 'Generated by UrbanDeploy')
            it.flush()
        }

        soapRedirectSettingTempFile.withOutputStream {
            def redirectProps = new Properties()
            redirectProps.setProperty('com.ibm.SOAP.ConfigURL', "file:${soapSettingTempFile.absolutePath}".toString())
            redirectProps.save(it, 'Generated by UrbanDeploy')
            it.flush()
        }

        commandArgs << "-p"
        commandArgs << soapRedirectSettingTempFile.name

    }
    catch (NumberFormatException nfe) {
        println "Invalid SOAP Connection Timeout value specified: $soapTimeout"
        System.exit 1
    }
}

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) {
    soapSettingTempFile.delete();
    soapRedirectSettingTempFile.delete();
    tempFile.delete();
}
System.exit(exitVal);
