#!/usr/bin/env groovy

import com.urbancode.air.*
import com.urbancode.ubuild.codestation.client.*
import com.urbancode.commons.httpcomponentsutil.HttpClientBuilder;

import com.urbancode.air.XTrustProvider;
import org.apache.http.entity.StringEntity;
import org.apache.http.client.HttpClient
import org.apache.http.client.*
import org.apache.http.client.methods.HttpPost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import java.net.URI;

XTrustProvider.install();

final def workDir = new File('.').canonicalFile
final def apTool = new AirPluginTool(this.args[0], this.args[1]);

final def props = apTool.getStepProperties();

def ubuildUrl = props['ubuildUrl']
final def ubuildUser = props['ubuildUser']
final def ubuildPassword = props['ubuildPassword']
final long buildLifeId = props['buildLifeId'].toLong()
final long processId = props['processId'].toLong()
final def delayTime = props['delayTime']
final def properties = props['properties']

def propArray = new groovy.json.JsonSlurper().parseText(properties)

while (ubuildUrl.endsWith("/")) {
    ubuildUrl = ubuildUrl.substring(0, ubuildUrl.length() - 1);
}

final def fullUrl = ubuildUrl + "/rest2/processRequests"
println(fullUrl)

def json = new groovy.json.JsonBuilder()
json(
    "buildLifeId" : buildLifeId,
    "processId" : processId,
    "delayTime" : delayTime,
    "properties" : propArray
)
println(json.toString())

StringEntity requestEntity = new StringEntity(json.toString(), "application/json", "UTF-8");

HttpClientBuilder builder = new HttpClientBuilder();
builder.setTrustAllCerts(true);

if (ubuildUser != null && ubuildPassword != null) {
    builder.setUsername(ubuildUser);
    builder.setPassword(ubuildPassword);
    builder.setPreemptiveAuthentication(true);
}

def client = builder.buildClient();

HttpPost method = new HttpPost(fullUrl);
method.setEntity(requestEntity);

HttpResponse response = client.execute(method);
int status = response.getStatusLine().getStatusCode();
if (status == HttpStatus.SC_OK || status == HttpStatus.SC_CREATED) {
    println "Successfully ran secondary process";
}
else {
    throw new Exception(String.format("%d", status));
}
