/*
 * Licensed Materials - Property of IBM Corp.
 * IBM UrbanCode Deploy
 * (c) Copyright IBM Corporation 2016, 2017. 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.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"))
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']
def timeout = props['timeout']

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)
    if (helper.getManagedServerStatus(targets[0]) != "NOT_RUNNING") {
        targets.each { target ->
        System.out.println("Stopping Target ${target}")
        if (helper.getManagedServerStatus(target) != "SHUTDOWN") {
                helper.stopManagedServer(target, force)
            }
        }

        def badStatuses = true
        long startTime = System.currentTimeMillis()
        while ((badStatuses) && (System.currentTimeMillis() - startTime < (timeout.toInteger()) * 1000)) {
            Thread.sleep(10000)
            badStatuses = false
            targets.each { target ->

                def status = helper.getManagedServerStatus(target)
                if (status instanceof List) {
                    status.each { serverStatusPair ->
                        if (serverStatusPair[1] != "SHUTDOWN") {
                            if (serverStatusPair[1] != "NOT_RUNNING") {
                                badStatuses = true
                            }
                        }
                        else {
                            println "Target ${serverStatusPair[0]} stopped successfully."
                        }
                    }
                } else {
                    println status
                    if (status != ("SHUTDOWN")) {
                        if (status != "NOT_RUNNING") {
                            badStatuses = true
                        }
                    }
                    else {
                        println "Target $target stopped successfully."
                    }
                }
            }
        }
        if (badStatuses) {
            targets.each { target ->
                System.out.println("Checking Target ${target}")
                def status = helper.getManagedServerStatus(target)
                if (status instanceof List) {
                    status.each { serverStatusPair ->
                        println "Target ${serverStatusPair[0]} failed to stop before timing out, remains in state ${serverStatusPair[1]}."
                    }
                }
                else {
                    println "Target ${target} failed to stop before timing out, remains in state ${status}."
                }

            }
            println "Targets failed to stop before timing out."
        }
        else {
            println "Targets stopped."
        }
    }
}
catch (Exception e) {
    e.printStackTrace()
    throw e
}
finally {
    helper.closeConn()
}