/*
* Licensed Materials - Property of IBM* and/or HCL**
* UrbanCode Deploy
* UrbanCode Build
* UrbanCode Release
* AnthillPro
* (c) Copyright IBM Corporation 2011, 2017. All Rights Reserved.
* (c) Copyright HCL Technologies Ltd. 2018. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*
* * Trademark of International Business Machines
* ** Trademark of HCL Technologies Limited
*/
import com.urbancode.air.AirPluginTool;

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

def props = apTool.getStepProperties();

def host = props['hostname'];
def port = props['port'];
def retries = props['retries'];
def interval = props['interval'];

def tryConnection = {
    boolean success = false;
    Socket skt = null;
    try {
        skt = new Socket(host, Integer.valueOf(port));
        success = true;
    }
    catch (Exception e) {
        success=false;
    }
    finally {
        if (skt != null) {
            try {
                 skt.close()
            }
            catch (IOException ioe) {
               //swallow
            }
        }
     }

     return success
}

boolean success = false;
int numTries = 1;
while (!success && numTries <= Integer.valueOf(retries)+1) {
    println "Trying to get connection to $host at $port #$numTries"
    success = tryConnection();
    if (!success) {
        println "Connection failed!";
        numTries ++;
        if (numTries <= Integer.valueOf(retries)){
            println  "Sleeping for $interval seconds"
            Thread.sleep(Long.valueOf(interval) * 1000);
        }
    }
    else {
        println "Connectivity to $host:$port is good."
    }
}

if (success) {
    System.exit(0);
}
println "A TCP connection cound not be made to $host:$port."
System.exit(1);
