import com.urbancode.air.plugin.wldeploy.WebLogicStatusHelper;
import com.urbancode.air.AirPluginTool;

final def workDir = new File('.').canonicalFile
def apTool = new AirPluginTool(this.args[0], this.args[1]);
def props = apTool.getStepProperties();
final def jmxUrl = props['jmxUrl'];
def user = props['user'];
def pass = props['password'];
final def configFile = props['configFile'];
final def keyFile = props['keyFile'];
def targets = props['targets'];
final def timeout = props['timeout'];
final def onFail = props['onFail'];

targets = targets.split(',');

try {
    WebLogicStatusHelper helper = new WebLogicStatusHelper();
    if (configFile) {
        user = helper.getUser(configFile, keyFile);
        pass = helper.getPass(configFile, keyFile);
    }
    helper.initConn(jmxUrl, user, pass);
    targets.each { target ->
        System.out.println("Starting Target ${target}");
        helper.startManagedServer(target);
    }

    def badStatuses = [];
    def failure = false;
    def currentState;
    badStatuses << "start";
    long startTime = System.currentTimeMillis();
    while (!badStatuses.isEmpty() && System.currentTimeMillis()-startTime<(timeout.toInteger())*1000) {
        Thread.sleep(10000);
        badStatuses.clear();
        targets.each { target ->
            System.out.println("Checking Target ${target}");
            def status = helper.getManagedServerStatus(target);
            if (status instanceof List) {
                status.each { serverStatusPair ->
                    println serverStatusPair;
                    if (serverStatusPair[1] != "RUNNING") {
                        badStatuses << [serverStatusPair[0], serverStatusPair[1]];
                    }
                }
            }
            else {
                println status;
                if (status != "RUNNING") {
                    badStatuses << [target, status];
                }
            }
        }
    }
    targets.each { target ->
        currentState = helper.getManagedServerStatus(target);
        apTool.setOutputProperty("state-$target", currentState);
        if (currentState != "RUNNING") {
            if (onFail == "fail") {
                failure = true;
            }
            println("Target $target failed to start before timing out, remains in state $currentState");
        }
    }
    apTool.storeOutputProperties();
}
catch (Exception e) {
    e.printStackTrace();
    throw e;
}
finally {
    helper.closeConn();
    if (failure == true) {
        println("Process will now exit.");
        System.exit(1);
    }
}