/*
* 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;

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 timeout = props['timeout']

def interval = props['interval']
def deleteTempFileOnFailure = Boolean.valueOf(props['deleteTempFileOnFailure'])

try {
    interval = Integer.valueOf(interval);
}
catch (NumberFormatException e) {
    interval = 10;
    println("Interval must be a valid integer");
    println("Using default of 10 seconds");
}

def connType = props['connType']
def host = props['host'];
def port = props['port'];
def additionalArgs = props['additionalArgs'];

File tempFile = File.createTempFile("temp", ".py", new File("."))
if (deleteTempFileOnFailure) {
    tempFile.deleteOnExit();
}
BufferedWriter temp = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempFile), "UTF-8"))
def cellarg = cell ? " -cell " + cell : "";

try {
    timeout = Integer.valueOf(timeout);
}
catch (NumberFormatException e) {
    timeout = 5 * 60;
    println("Timeout must be a valid integer!");
    println("Using default timeout of " + 5 * 60 + " seconds.");
}

def invoke = "";
if (server == null || server.startsWith('${p:') || server.trim() == "") {
    invoke = """
import java.lang.System as system
import java.lang.Thread as thread
startTime = system.currentTimeMillis()
endTime = startTime + (${timeout} * 1000)
done = 0
timedout = 0

while done == 0:
    object = AdminControl.queryNames('type=Cluster,name=${cluster},*');
    if object == None or object.strip() == '':
        print 'Object not found... either it does not exist or is not running'
    else:
        status = AdminControl.invoke(object, 'getState').strip().lower();
        if status.find('running') == -1 and status.find('started') == -1:
            print 'Status not in running state: ' + status;
        else:
            print 'Object in running state: ' + status
            done = 1

    if endTime < system.currentTimeMillis():
        timedout = 1 - done
        done = 1
    
    if done == 0:
        thread.sleep(${interval} * 1000)
    
if timedout == 1:
    print "Timeout Waiting for Cluster to be ready!"
    sys.exit(1)

sys.exit(0)
""";
}
else {
    invoke = """
import java.lang.System as system
import java.lang.Thread as thread
startTime = system.currentTimeMillis()
endTime = startTime + (${timeout} * 1000)
done = 0
timedout = 0

while done == 0:
    object = AdminControl.queryNames('type=Server,node=${node},process=${server},*')
    if object == None or object.strip() == '':
        print 'Object not found... either it does not exist or is not running'
    else:
        status = AdminControl.invoke(object, 'getState').strip().lower();
        if status.find('running') == -1 and status.find('started') == -1:
            print 'Status not in running state: ' + status;
        else:
            print 'Object in running state: ' + status;
            done = 1

    if endTime < system.currentTimeMillis():
        timedout = 1 - done
        done = 1
    
    if done == 0:
        thread.sleep(${interval} * 1000)
    
if timedout == 1:
    print "Timeout Waiting for Server to be ready!"
    sys.exit(1)

sys.exit(0)
""";
}

temp.write(invoke, 0, invoke.length());
System.out.print(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";
}

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

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


System.out.println("")
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.consumeProcessOutput(outPrint, outPrint);
statusProc.waitForOrKill(timeout * 1100);
def exitVal = statusProc.exitValue();
if (exitVal == 0) {
    tempFile.delete();
}
System.exit(exitVal);
