#!/usr/bin/env groovy

import com.urbancode.air.AirPluginTool

def apTool = new AirPluginTool(this.args[0], this.args[1])
def props = apTool.getStepProperties()
final def helper = new F5Helper(props)
final def doWait = Boolean.valueOf(props['doWaitForConnectionClose'])
final def sleepInterval = (props['sleepInterval'])?Long.valueOf(props['sleepInterval']):5

try {
    helper.disableNodeInPool()
    if (doWait) {
        def currentConnections = helper.getNodeActiveConnections()
        while(currentConnections > 0) {
            println("Waiting for $currentConnections to close, sleep for $sleepInterval second(s)")
            sleep(sleepInterval * 1000, {println("Waiting aborted!"); return true})
            currentConnections = helper.getNodeActiveConnections()
        }
        println("All connections closed, done waiting.")
    }
}
catch (Exception e) {
    e.printStackTrace()
    System.exit(1)
}
