
import com.urbancode.air.AirPluginTool
/**
 * @author Mike Samano (mss2@urbancode.com)
 */

final def apTool = new AirPluginTool(this.args[0], this.args[1])

final def props = apTool.getStepProperties()

final def serverUrl = props['serverURL']
final def username = props['username']
final def password = props['password']
final def serviceGroup = props['serviceGroup']
final def allowedStates = props['allowedStates']
final def timeoutString = props['timeout']


println "Server URL: $serverUrl"
println "Username: $username"
println "Service Group: ${serviceGroup}"
println "Allowed member states: ${allowedStates}"
println ''

def boolean loggedIn = false
def boolean hasErrors = false
def NetScalerRestHelper helper


try {

    def allowedStatesList = new ArrayList()
    allowedStates.split('[,]').each {
        allowedStatesList.add(it.toLowerCase().trim())
    }

    def timeout = timeoutString.toInteger()
    def startTime = new Date().time

    helper = new NetScalerRestHelper(serverUrl)

    println "Get service group bindings for '${serviceGroup}'"

    def done = false
    while (!done) {
        try{
            def sgBindingJson = helper.getServiceGroupBindings(serviceGroup, username, password)
            def bindingArray = sgBindingJson.servicegroup_binding
            def memberArray = bindingArray.get(0)?.servicegroup_servicegroupmember_binding

            def failures = []
            println "  Checking service group members:"

            memberArray.each {
                def serverName = it.servername.getAsString()
                def port = it.port.getAsInt()
                def serverState = it.svrstate.getAsString()

                int rowSpacing = 60 - serverName.size()
                def formatString = "    %s:%d%${rowSpacing}s\n"
                printf(formatString, [serverName, port, serverState])

                if (!allowedStatesList.contains(serverState.trim().toLowerCase())) {
                    hasErrors = true
                    failures << "    Group member '${serverName}' state '${serverState}' is not contained in [${allowedStates}]"
                }
            }

            println()
            failures.each { println it }
            println()
        }
        catch (Exception e) {
            println e.message
            hasErrors = true
            done = true
        }

        def duration = (new Date().time - startTime) / 1000


        if (done) {
            println "\nFailed to check one or more members"
        }
        else if (!hasErrors) {
            done = true
            println "\nAll members match expected status"
        }
        else if (duration > timeout) {
            done = true
            println "\nReached timeout before all members matched expected status"
        }
        else {
            sleep 1000
            hasErrors = false
            println "\nRetrying..."
        }
    }
}
catch (Exception ee) {
    println ee.message
    hasErrors = true
}
finally {
    if (loggedIn && helper) {
        try {
            helper.logout()
        }
        catch (Exception e) {
            println e.message
        }
    }
}

if (hasErrors) {
    System.exit 1
}
else {
    System.exit 0
}
