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 serviceList = props['serviceList']
final def expectedState = props['expectedState']
final def timeoutString = props['timeout']


println "Server URL: $serverUrl"
println "Username: $username"
println "Service Group List: ${serviceList.split('[\n,]').join(',')}"
println ''

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

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

    helper = new NetScalerRestHelper(serverUrl)

    def done = false
    while (!done) {
        serviceList.split('[\n,]').each {
            if (it && it.trim().length() > 0) {
                try {
                    def serviceGroup = helper.getServiceGroup(it.trim(), username, password)
                    def sgArray = serviceGroup.'servicegroup'
                    def serviceGroupState = sgArray.get(0)?.'state'.getAsString()

                    if (!expectedState.equals(serviceGroupState)) {
                        println "${it}: ${serviceGroupState} - (Does not match expected state ${expectedState})"
                        hasErrors = true
                    }
                    else {
                        println "${it}: ${serviceGroupState}"
                    }
                }
                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 service groups"
        }
        else if (!hasErrors) {
            done = true
            println "\nAll service groups match expected status"
        }
        else if (duration > timeout) {
            done = true
            println "\nReached timeout before all service groups 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
}
