/*
* 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.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 com.urbancode.air.AirPluginTool
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()


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

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}")

XTrustProvider.install()

HttpHelper helper

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

if ( charset ) {
    helper.setCharset(charset);
}

DefaultHttpClient client = helper.client


def success = true;
def method = new HttpGet(url)
def response = client.execute(method)
def body = helper.getBody(response)
def status = response.getStatusLine().getStatusCode()
if(status <200 || status > 299) {
    println("Error result code recieved : ${status}")
    println(body)
    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")
    println(body)
    if (!failIfFound) {
        success = false
    }
}

if (!success) System.exit(1)

System.exit 0
