#!/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.LocalLBPoolBindingStub
import iControl.LocalLBPoolLocator
import iControl.ManagementPartitionBindingStub

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

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()
    
    iControl.ManagementPartitionBindingStub partition = (iControl.ManagementPartitionBindingStub)new iControl.ManagementPartitionLocator().getManagementPartitionPort(new java.net.URL(connectionString));
    partition.setTimeout(timeout * 1000)
    partition.set_active_partition(partitionName);
    
    def LocalLBPoolBindingStub poolStub

    def getState = {
        try {
            return poolStub.get_object_status([poolName] as String[])
        }
        catch (Exception e) {
            return null
        }
    }

    println("Connecting to server ${props['serverURL']} using timeout of $timeout second(s)")
    poolStub =
        new LocalLBPoolLocator().getLocalLBPoolPort(new java.net.URL(connectionString)) as LocalLBPoolBindingStub
    poolStub.setTimeout(timeout * 1000)

    def currentState = getState()

    if (!currentState) {
        println "Pool $poolName does not exist"
    }
    else {
        println "Deleting $poolName "
        poolStub.delete_pool(
                [poolName] as String[])
        println "Pool successfully deleted!"
    }
}
catch (Exception e) {
    e.printStackTrace()
    System.exit(1)
}
