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


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);
}
final def jmxUrl = props['jmxUrl'];
def user = props['user'];
def pass = props['password'];
final def configFile = props['configFile'];
final def keyFile = props['keyFile'];
final def force = Boolean.valueOf(props['force']);
def targets = props['targets'];

targets = targets.split(',');

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

    def badStatuses = [];
    badStatuses << "start";
    while (!badStatuses.isEmpty()) {
        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] != "SHUTDOWN") {
                        badStatuses << [serverStatusPair[0], serverStatusPair[1]];
                    }
                }
            }
            else {
                println status;
                if (status != "SHUTDOWN") {
                    badStatuses << [target, status];
                }
            }
        }
    }
}
catch (Exception e) {
    e.printStackTrace();
    throw e;
}
finally {
    helper.closeConn();
}