#!/usr/bin/env groovy
/*
* Licensed Materials - Property of IBM* and/or HCL**
* UrbanCode Deploy
* UrbanCode Build
* UrbanCode Release
* AnthillPro
* (c) Copyright IBM Corporation 2011, 2017. All Rights Reserved.
* (c) Copyright HCL Technologies Ltd. 2018. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*
* * Trademark of International Business Machines
* ** Trademark of HCL Technologies Limited
*/

import com.urbancode.air.AirPluginTool;
import com.urbancode.ud.client.VersionClient;
import com.urbancode.ds.client.AddVersionFilesCommand;
import org.apache.http.impl.client.DefaultHttpClient;
import com.urbancode.commons.httpcomponentsutil.HttpClientBuilder

def apTool = new AirPluginTool(this.args[0], this.args[1]);

def props = apTool.getStepProperties();

def udUser = apTool.getAuthTokenUsername();
def udPass = apTool.getAuthToken();
def weburl = System.getenv("AH_WEB_URL");
def componentName = props['componentName'];
def versionName = props['versionName'];

com.urbancode.commons.util.ssl.XTrustProvider.install()

//upload file props
def uploadFiles = props['uploadFiles'];
def includes = props['includes']?.split('\n') as String[];
def excludes = props['excludes']?.split('\n') as String[];
def saveFileExecuteBits = props['saveFileExecuteBits'] != null && Boolean.valueOf(props['saveFileExecuteBits']);

def proxyHost = System.env['PROXY_HOST'] ? System.env['PROXY_HOST'] : null
def proxyPortString = System.env['PROXY_PORT'] ? Integer.valueOf(System.env['PROXY_PORT']) : null
int proxyPort = 80;

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

builder.setUsername(udUser);
builder.setPassword(udPass);
builder.setPreemptiveAuthentication(true);

if (proxyHost) {
    if (proxyPortString) {
       try {
           proxyPort = Integer.valueOf(proxyPortString);
       }
       catch (NumberFormatException e) {
           System.out.println("Using 80 for proxy port!");
       }
    }
    else {
           System.out.println("Using 80 for proxy port!");
    }

    builder.setProxyHost(proxyHost);
    builder.setProxyPort(proxyPort);
}

DefaultHttpClient client = builder.buildClient();



def udRestClient = new VersionClient(new URI(weburl), udUser, udPass);

println "Creating version $versionName on component $componentName";
def versionId = udRestClient.createVersion(componentName, versionName, "");


if (Boolean.valueOf(uploadFiles)) {
    def command = new AddVersionFilesCommand(weburl, client, componentName,
                                            versionName, new File('.'), null, includes, excludes,
                                             saveFileExecuteBits, true, null, null);
    command.execute();
}

apTool.setOutputProperty("versionId", versionId.toString());
apTool.storeOutputProperties();
