/*
* 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.commons.httpcomponentsutil.HttpClientBuilder;

import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.HttpRequest;
import org.apache.log4j.Logger;
import org.codehaus.groovy.runtime.StackTraceUtils;

import com.urbancode.air.XTrustProvider
import com.urbancode.air.plugin.DeployTools.HttpHelper

final def workDir = new File('.').canonicalFile
final def airTool = new AirPluginTool(args[0], args[1])
final def props = airTool.getStepProperties()
final def debug = Boolean.getBoolean('com.urbancode.air.DeployTools.DEBUG');

def timeout = props['timeout']
def user = props['user']
def url = props['url']
def verifyString = props['verifyString']
def failIfFound = props['failIfFound'].toBoolean()
def base_url = new URL(url).getHost()
def port = new URL(url).getPort()
def password = (props['password']?props['password']:(props['passScript']?props['passScript']:null))
def retry_timeout = Long.parseLong(props['retryTimeout'])
def max_wait_time = Long.parseLong(props['maxWaitTime'])

println("URL : ${url}")
println("Verify String : ${verifyString}")
println("Timeout : " + timeout)
println("User : ${user}")
println("Fail If Found: $failIfFound")
println("Host : ${base_url}")
println("Port : ${port}")
println("Max Wait Time : ${max_wait_time} s")
println("Retry wait time : ${retry_timeout} ms")

XTrustProvider.install()

HttpHelper helper

if(user && password) {
    helper = new HttpHelper(airTool, user, password)
}
else {
    helper = new HttpHelper(airTool)
}
DefaultHttpClient client = helper.client

def method = null
def response = null
def body = null
def status = 0
def success
def startTime = System.currentTimeMillis()
def latestException = null;
while (System.currentTimeMillis() - startTime < max_wait_time*1000) {
    try {
        success = true
        latestException = null;
        method = new HttpGet(url)
        response = client.execute(method)
        status = response.getStatusLine().getStatusCode()
        body = helper.getBody(response)
        if(status <200 || status > 299) {
            println("Error result code received : ${status}")
            //println(response)
            success = false
        }
        else if(!body) {
            println("No response received from url : ${url}")
            success = false
        }
        else if(body =~ verifyString) {
            println("Response matches the verify String")
            if (failIfFound) {
                success = false
            }
        }
        else {
            println("Response did not match the verify string")
            if (debug) {
                println(response);
            }
            if (!failIfFound) {
                success = false
            }
        }
    }
    catch (Exception e) {
        success = false;
        println "Error occurred: " + e.getMessage();
        if (debug) {
            StackTraceUtils.sanitize(e).printStackTrace();
        }
        latestException = e;
    }
    finally {
        if (success) {
            break
        }
        else {
            sleep(retry_timeout)
        }
    }
}

if (!success) {
    if (latestException != null) {
        println "Last try failed with exception.";
        StackTraceUtils.sanitize(latestException).printStackTrace();
    }
    System.exit(1);
}
else {
    System.exit(0);
}
