#!/usr/bin/env groovy
/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Build
* IBM UrbanCode Deploy
* IBM UrbanCode Release
* IBM AnthillPro
* (c) Copyright IBM Corporation 2002, 2013. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*/

import com.urbancode.air.AirPluginTool
import com.urbancode.air.XTrustProvider
import iControl.CommonIPPortDefinition

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

final def props = apTool.getStepProperties()

final def serverUrlArray = props['serverURL']?.split('://') as String[]
final def username = props['username']
final def password = props['password']
final def timeout = Integer.parseInt(props['timeout'])

final def poolName = props['poolName']
final def nodeAddress = props['nodeAddress'] as String
final def nodePort = Long.parseLong(props['nodePort']) as long

try {
    if (serverUrlArray.length != 2) println("Malformed server URL: ${props['serverURL']} missing <protocol>://")
    if (serverUrlArray[1].endsWith('/')) serverUrlArray[1] = serverUrlArray[1].substring(0, serverUrlArray[1].length() - 1)

    final def connectionString = serverUrlArray[0] + "://" + username + ":" + password + "@" +
            serverUrlArray[1] + "/iControl/iControlPortal.cgi"

    XTrustProvider.install()
    def iControl.LocalLBPoolBindingStub poolStub
    def iControl.LocalLBPoolMemberBindingStub poolMemberAddress

    def getState = {
        for (member in poolMemberAddress.get_session_enabled_state(poolName)[0]) {
            if (member.member.address.equals(nodeAddress) && member.member.port == nodePort) return member.session_state
        }
    }

    println("Connecting to server ${props['serverURL']} using timeout of $timeout second(s)")
    poolMemberAddress =
        new iControl.LocalLBPoolMemberLocator().getLocalLBPoolMemberPort(new java.net.URL(connectionString)) as
        iControl.LocalLBPoolMemberBindingStub
    poolMemberAddress.setTimeout(timeout * 1000);
    def currentState = getState()

    if (!currentState) {
        println "Node $nodeAddress:$nodePort is not part of pool $poolName"
    }
    else {
        poolStub =
            new iControl.LocalLBPoolLocator().getLocalLBPoolPort(new java.net.URL(connectionString)) as
            iControl.LocalLBPoolBindingStub

        poolStub.setTimeout(timeout * 1000)

        println "Removing node $nodeAddress:$nodePort from pool $poolName"
        def node = new CommonIPPortDefinition(nodeAddress, nodePort)
        def nodeArray = new CommonIPPortDefinition[1][1]
        nodeArray[0][0] = node
        poolStub.remove_member(
                [poolName] as String[],
                nodeArray
        )
        println "Node removed successfully!"
    }
}
catch (Exception e) {
    e.printStackTrace()
    System.exit(1)
}
