#!/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, 2015. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*/

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}")
def pkgZipFile = new File(baseDirectory.path+"/${packageZipFileName}")

def packageFilesDownloadStatus = true

println "";
if (!pkgManifestFile.exists()) {
    println "Error: ${pkgManifestFile} not found in CodeStation"
    packageFilesDownloadStatus = false;
}

if (isGenericOnlyVersion(pkgManifestFile.getCanonicalPath())) {
    apTool.setOutputProperty("genericonly", "true");
} else {
    apTool.setOutputProperty("genericonly", "false");
    if (!pkgZipFile.exists()) {
        println "Error: ${pkgZipFile} not found in CodeStation";
        packageFilesDownloadStatus = false;
    }
}

apTool.storeOutputProperties()

if (!packageFilesDownloadStatus) {
    println "";
    println("Version artifacts not found in CodeSation. Make sure the version is created by BUZTOOL and ucd.repository.type is set to CODESTATION in PROFILE.");
    System.exit(1);
}


def isGenericOnlyVersion(manifestFilePath) {
    def ret = false;
    
    def manifestFile = new File(manifestFilePath);
    if(!manifestFile.exists()){
        throw new IllegalArgumentException("${manifestFilePath} not found. Please make sure it was downloaded successfully.");
    }
    def manifest = new XmlSlurper(false, false).parse(manifestFile)
    

    def allAddDatasetsContainers = manifest.container.findAll({node->
        node.@type != "GENERIC"
    });
    if (allAddDatasetsContainers.size() > 0) {
        return false;
    }
    
    def allDeleteDatasetsContainers = manifest.deleted.container.findAll({node->
        node.@type != "GENERIC"
    });
    if (allDeleteDatasetsContainers.size()>0){
        return false;
    }
    
    def allGenericContainers = manifest.container.findAll({node->
        node.@type == "GENERIC"
    });    
    if (allGenericContainers.size()>0) {
        ret = true;
    }
    
    return ret;
}