#!/usr/bin/env groovy

import java.io.IOException;

import com.urbancode.air.*
import com.urbancode.ubuild.codestation.client.*

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

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 def buildLifeId = props['buildLifeId']
final def label = props['labelName']
final def labelDependencies = props['labelDependency']

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

final def fullUrl = ubuildUrl + "/rest2/build-lives/" + buildLifeId + "/labels";
println(fullUrl);

def json = new groovy.json.JsonBuilder()
json("buildLifeId" : buildLifeId, "label" : label, "labelDependencies" : labelDependencies)
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 assigned label";
}
else {
    throw new Exception(String.format("%d", status));
}