#!/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.HttpPut;
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.URLEncoder;

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 snapshotId = props['snapshotId']
final def statusName = props['statusName']
final def filePath = props['filePath']
final def comment = props['comment']
final def fileDescription = props['fileDescription']
def deployUrl = System.getenv("AH_WEB_URL");

if (!releaseUrl.endsWith("/")) releaseUrl+="/";
if (!deployUrl.endsWith("/")) deployUrl+="/";

def statusSanitized =  statusName.replaceAll(" ", "%20")

final def deployTarget = deployUrl+"rest/deploy/snapshot/"+snapshotId+"/status/"+statusSanitized;
final def releaseTarget = releaseUrl + "version/externalId/"+snapshotId+"/status/"+URLEncoder.encode(statusName,"UTF-8");

println("Release Target=>"+releaseTarget)
println("Deploy Target=>"+deployTarget)
println("SnapshotId=>"+snapshotId)
println("Status=>"+statusName)
println("Comment=>"+comment)
println("File=>"+filePath)
println("File Description=>"+fileDescription)

def deployLogin = "PasswordIsAuthToken";
def deployPassword = "{\"token\": \""+System.getenv('AUTH_TOKEN')+"\"}";

HttpClientBuilder builderDeploy = new HttpClientBuilder();
builderDeploy.setTrustAllCerts(true);
builderDeploy.setUsername(deployLogin);
builderDeploy.setPassword(deployPassword);
builderDeploy.setPreemptiveAuthentication(true);

def clientDeploy = builderDeploy.buildClient();

//Add status to the snapshot in Deploy
def HttpPut put = new HttpPut(deployTarget);
HttpResponse responsePut = clientDeploy.execute(put);
int status = responsePut.getStatusLine().getStatusCode();
if (status == HttpStatus.SC_NO_CONTENT) {
     println "Snapshot Status successfully added in Deploy";
}
else {
    println "Snapshot Status not added";
    throw new Exception("Could not add status to a snapshot in Deploy");
}

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

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

sendMultiPart(builder, releaseTarget, filePath, comment, fileDescription);

void sendMultiPart(HttpClientBuilder builder, String url, String filePath, String comment, String fileDescription) {
    
    def client = builder.buildClient();
    def HttpPost post = new HttpPost(url);
    def MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    
    if (!filePath.equals("")) {
        def File file = new File(filePath);
        if (file.exists()) {
            println("Attachment exists")
            println("FileName => "+file.name)
            // For File parameters
            entity.addPart( "file", new FileBody((file ), "application/octet-stream" ));
        }
        else {
            println("Attachment does not exists")
            throw new Exception("Attachment does not exists");
        }
    }
    else {
        println("No attachment added")
    }
    
    entity.addPart("comment", new StringBody(comment, "text/plain", Charset.forName( "UTF-8" )));
    entity.addPart("attachmentDescription", new StringBody(fileDescription, "text/plain", Charset.forName( "UTF-8" )));
     
    post.setEntity( entity );
     
    HttpResponse response = client.execute(post);
    int status = response.getStatusLine().getStatusCode();
    if (status == HttpStatus.SC_OK || status == HttpStatus.SC_CREATED) {
         println "Snapshot Status successfully added in Release";
    }
    else {        
        HttpEntity entityResponse = response.getEntity();
        String responseString = EntityUtils.toString(entityResponse, "UTF-8");
        
        println("--------------RESPONSE ERROR---------------")
        println(responseString.replace("\n\r", ""))
        println("------------------------------------------")
        
        throw new Exception(String.format("%d", status));
    }
 }