import com.urbancode.air.AirPluginTool
/**
 * @author Varban Vassilev (vvv@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 isGraceful = props['isGraceful']
final def timeout = props['timeout']

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

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

try {
    timeout.toInteger()

    helper = new NetScalerRestHelper(serverUrl)

    // login
    helper.login(username, password)
    loggedIn = true

    // enable each server in the list
    serviceList.split('[\n,]').each {
        if (it && it.trim().length() > 0) {
            try {
                helper.disableServiceGroup(it.trim(), timeout.trim(), isGraceful)
            }
            catch (Exception e) {
                println e.message
                hasErrors = true
            }
        }
    }

    if (hasErrors) throw new Exception('Could not disable all service groups successfuly!')

}
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
}
