#!/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 org.apache.http.client.methods.HttpGet
import org.apache.http.util.EntityUtils
import org.codehaus.jettison.json.JSONObject

import com.ibm.uclab.csrepl.client.ops.Download
import com.ibm.uclab.csrepl.client.ops.DownloadSync
import com.urbancode.air.AirPluginTool
import com.urbancode.commons.httpcomponentsutil.HttpClientBuilder

def apTool = new AirPluginTool(args[0], args[1])
def final packageZipFileName = "package.zip";
def final packageManifestFileName = "packageManifest.xml";

def PROXY_HOST = System.env['PROXY_HOST']
def PROXY_PORT = System.env['PROXY_PORT']
if (PROXY_PORT != null) {
    PROXY_PORT = Integer.valueOf(PROXY_PORT)
}

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

def repositoryType = props['repositoryType']?.trim();
def versionName = props['versionName']?.trim();
def versionId = UUID.fromString(props['versionId'])
def resourceId = props['resourceId']?.trim();

if (!"CODESTATION".equalsIgnoreCase(repositoryType)) {
    if ("HFS".equalsIgnoreCase(repositoryType)) {
        println("Version ${versionName}($versionId) is stored in zOS HFS. Use Copy Artifacts or FTP Artifacts plug-in steps to retrieve the version artifacts.");
        println("Download failed.");
    } else {
        println("Version ${versionName}($versionId) is not stored in CodeStation.");
        println("Download failed.");
    }
    System.exit(1);
}

workDir = new File(workDir.absolutePath + File.separator + resourceId + File.separator + versionName).canonicalFile;

def directoryOffset = props['directoryOffset']
def compId = props['compId']
def serverURL = props['serverUrl']
def charset = Util.getCharset(props)

def baseDirectory = workDir
if (directoryOffset) {
    baseDirectory = new File(workDir, directoryOffset).canonicalFile
}

def includes = [packageZipFileName, packageManifestFileName]

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

Util.configureLogging()

//
// Download the files
//
def csClient = Util.getCodestationClient(
    serverURL, 
    false, 
    apTool.getAuthTokenUsername(), 
    apTool.getAuthToken())

def op = new Download(csClient, baseDirectory, versionId)

op.setIncludes(includes)
op.setOutputCharset(charset)

println "Artifact source: ${csClient.url}"
println "Working directory: ${baseDirectory.path}"
println "Offset ${directoryOffset}"
println ""

op.run()

def pkgManifestFile = new File(baseDirectory.path+"/${packageManifestFileName}")

if (!pkgManifestFile.exists()) {
    println "Error: ${packageManifestFileName} not found in CodeStation"
    System.exit(1);
}
