/*
* 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

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 nodeAddress = props['nodeAddress'] as String
final def partitionName = props['partition']

def m_interfaces = new iControl.Interfaces();

def connectionString = serverUrlArray.length > 1? serverUrlArray[1] : serverUrlArray[0]
if (connectionString.endsWith('/')) {
    connectionString = connectionString.substring(0, connectionString.length() - 1)
}
XTrustProvider.install()
m_interfaces.initialize(connectionString, username, password)

def partitionBinding = m_interfaces.getManagementPartition()
partitionBinding.set_active_partition(partitionName)

def stepStatus
String[] nodeAddressArray = [nodeAddress]
def nodeAddressBinding = m_interfaces.getLocalLBNodeAddress()
def objectStatuses = nodeAddressBinding.get_object_status(nodeAddressArray)
def enabledStates = nodeAddressBinding.get_session_enabled_state(nodeAddressArray)
for (objectStatus in objectStatuses) {
    def isEnabled = objectStatus.getEnabled_status()
    def isAvailable = objectStatus.getAvailability_status()
    
    if (isEnabled == iControl.LocalLBEnabledStatus.ENABLED_STATUS_ENABLED) {
        println "Node ${nodeAddress} is enabled."
    }
    else {
        println "Node ${nodeAddress} is disabled. Failing the step."
        stepStatus = "Failure"
    }
    
    if (isAvailable == iControl.LocalLBAvailabilityStatus.AVAILABILITY_STATUS_RED ||
        isAvailable == iControl.LocalLBAvailabilityStatus.AVAILABILITY_STATUS_NONE ) {
        println "Node ${nodeAddress} is not available. Failing the step."
        stepStatus = "Failure"
    }
    else {
        println "Node ${nodeAddress} is available."
    }
}

apTool.setOutputProperty("Status", stepStatus ?: "Success")
apTool.setOutputProperties()
