#!/usr/bin/env groovy
/*
 * Licensed Materials - Property of IBM Corp.
 * IBM UrbanCode Release
 * (c) Copyright IBM Corporation 2014. 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.*
import com.urbancode.commons.httpcomponentsutil.HttpClientBuilder;

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

XTrustProvider.install();

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

def props = apTool.getStepProperties();


def releaseUrl = props['releaseUrl']
final def releaseUser = props['releaseUser']
final def releasePassword = props['releasePassword']
final def environmentId = props['environmentId']
final def propertyReleaseName = props['propertyReleaseName']
final def propertyPhaseName = props['propertyPhaseName']

println("ENV UUID=>"+environmentId)

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

final def fullUrl = releaseUrl + "/environmentReservation/releaseForEnvironment/"+environmentId;
println("REST END POINT=>"+fullUrl)

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

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

def client = builder.buildClient();

HttpGet methodGet = new HttpGet(fullUrl);
HttpResponse responseGet = client.execute(methodGet);

int status = responseGet.getStatusLine().getStatusCode();

println("RESPONSE CODE=>"+responseGet.getStatusLine().getStatusCode())

if (status == HttpStatus.SC_OK) {
    println "Successfully contacted Release";
    
    String resultBody = EntityUtils.toString(responseGet.getEntity());
    EntityUtils.consume(responseGet.getEntity());

    if (resultBody != null) {
        println("RESPONSE BODY=>"+resultBody)
        def slurper = new groovy.json.JsonSlurper()
        def releaseInfo = slurper.parseText(resultBody)
        //We setup the output properties
        apTool.setOutputProperty(propertyReleaseName, releaseInfo.name);
        apTool.setOutputProperty(propertyPhaseName, releaseInfo.phase);
        apTool.storeOutputProperties();
    }
    else {
        throw new Exception("Response body is empty");
    }
}
else {
    HttpEntity entity = responseGet.getEntity();
    String responseString = EntityUtils.toString(entity, "UTF-8");
    
    println("--------------RESPONSE ERROR---------------")
    println(responseString.replace("\n\r", ""))
    println("------------------------------------------")
    throw new Exception(String.format("%d", status));
}
