/*
* Licensed Materials - Property of IBM* and/or HCL**
* UrbanCode Deploy
* (c) Copyright IBM Corporation 2013, 2017. All Rights Reserved.
* (c) Copyright HCL Technologies Ltd. 2018. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*
* * Trademark of International Business Machines
* ** Trademark of HCL Technologies Limited
*/
import com.urbancode.air.AirPluginTool
import com.urbancode.air.plugin.wldeploy.WebLogicStatusHelper

final def workDir = new File('.').canonicalFile
AirPluginTool apTool = new AirPluginTool(this.args[0], this.args[1])
def props = apTool.getStepProperties(System.getenv("UCD_SECRET_VAR"), System.getenv("UCD_SUITE_VAR"))

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']
def app = props['app']
def wantedStatus = props['wantedStatus']
def timeout = props['timeout']
def badStatuses = []
badStatuses <<"start"

targets = targets.split(',')
long startTime = System.currentTimeMillis()

try {
    WebLogicStatusHelper helper = new WebLogicStatusHelper()
    if (configFile) {
        user = helper.getUser(configFile, keyFile)
        pass = helper.getPass(configFile, keyFile)
    }
    helper.initConn(jmxUrl, user, pass)
    def fail
    while ((!badStatuses.isEmpty()) && (System.currentTimeMillis() - startTime < (timeout.toInteger()) * 1000)) {
        fail = false
        badStatuses.clear()
        targets.each { target ->
            System.out.println("Checking Target ${target}")
            def status = helper.getAppState(app,target)
            if (status != wantedStatus) {
                badStatuses << [target, status]
            }
            else {
                println "App in correct state: ";
                println "${target}, ${status}"
            }
        }
        if (!badStatuses.isEmpty()) {
            println "App not in correct state on some targets: "
            println badStatuses
            fail = true
            Thread.sleep(10000)
        }
    }
    helper.closeConn()

    if (fail) {
        println "Wait For Application timed out after ${timeout} seconds."
        System.exit(1)
    }
    else {
        System.exit(0)
    }
}
catch (Exception e) {
    e.printStackTrace()
    throw e
}
