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 serverList = props['serverList']

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

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

try {
    helper = new NetScalerRestHelper(serverUrl)

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

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

    if (hasErrors) throw new Exception('Could not enable all servers 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
}
