#!/usr/bin/env groovy
/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Build
* IBM UrbanCode Deploy
* IBM UrbanCode Release
* IBM AnthillPro
* (c) Copyright IBM Corporation 2002, 2014. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*/

import java.io.IOException
import java.net.URLEncoder
import java.nio.charset.Charset
import java.util.UUID

import com.urbancode.air.AirPluginTool
import com.ibm.uclab.csrepl.client.ops.Upload

import org.apache.http.HttpResponse
import org.apache.http.HttpStatus
import org.apache.http.client.methods.HttpGet
import org.apache.http.impl.client.DefaultHttpClient
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler
import org.apache.http.util.EntityUtils
import org.codehaus.jettison.json.JSONObject

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

def AGENT_HOME = new File(System.env['AGENT_HOME'])

def workDir = new File('.').canonicalFile
def props = apTool.getStepProperties()

def baseDirectory = new File(props['directoryOffset'])
def includes = props['fileIncludePatterns']?.readLines()
def excludes = props['fileExcludePatterns']?.readLines()
def extensions = props['extensions']?.split(",") as List
def saveFileExecuteBits = props['saveFileExecuteBits'] != null && Boolean.valueOf(props['saveFileExecuteBits'])
def versionId = UUID.fromString(props['versionId'])
def serverURL = props['serverUrl']
def outputFilePath = props['outputFile']

def agentProps = new Properties()
def agentInstalledProps = new File(AGENT_HOME, "conf/agent/installed.properties")
agentInstalledProps.withInputStream {
    agentProps.load(it)
}

def systemCharset
if (agentProps['system.default.encoding']){
    systemCharset = Charset.forName(agentProps['system.default.encoding'])
}

//
// Validation
//

if (baseDirectory.isFile()) {
    throw new IllegalArgumentException("Base directory ${baseDirectory} is a file!")
}

Util.configureLogging()

//
// Collect the files to upload
//
def forceUseServerUrl = true
def csClient = Util.getCodestationClient(
    serverURL, 
    forceUseServerUrl, 
    apTool.getAuthTokenUsername(), 
    apTool.getAuthToken())

//
// Upload the files
//

def op = new Upload(csClient, baseDirectory, versionId)
op.setIncludes(includes)
op.setExcludes(excludes)
op.setTextFileCharset(systemCharset)
op.setTextFileExtensions(extensions)
op.setSaveExecuteBits(saveFileExecuteBits)
op.run()
