#!/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 java.io.IOException;
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.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.entity.mime.content.FileBody
import org.apache.http.HttpEntity;
import java.nio.charset.Charset;

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

final def fullUrl = releaseUrl + "integrationProvider/updateApplication/"+application;
println("URL=>"+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();
def HttpPost post = new HttpPost(fullUrl);

HttpResponse response = client.execute(post);
int status = response.getStatusLine().getStatusCode();
if (status == HttpStatus.SC_OK || status == HttpStatus.SC_CREATED) {
     println "Application successfuly updated";
}
else {
    if (response.getStatusLine().reasonPhrase != null) {
        println "Error=>"+response.getStatusLine().reasonPhrase;
    }
    
    HttpEntity entity = response.getEntity();
    String responseString = EntityUtils.toString(entity, "UTF-8");
    
    println("--------------RESPONSE ERROR---------------")
    println(responseString.replace("\n\r", ""))
    println("------------------------------------------")
    
    throw new Exception(String.format("%d", status));
}
