#!/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]

// Delete base directory if present for zOS component version
if (baseDirectory.exists() && baseDirectory.isDirectory()) {
            println "Deleting base directory - $baseDirectory"
            baseDirectory.deleteDir();
}

//
// 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);
}

if (isSecondVersion(pkgManifestFile)) {

    def zipFilePath = "${baseDirectory.path}/${packageZipFileName}"
    def zipFile = new File(zipFilePath)

    // See if file exist
    if (zipFile.exists()) {

        // Extract package.zip for version-2
        def sout = new StringBuilder(), serr = new StringBuilder()
        String[] cmdArgs = ["pax", "-r", "-vf", zipFilePath]
        final def processBuilder = new ProcessBuilder(cmdArgs).directory(baseDirectory)
        final def process = processBuilder.start()
        process.out.close() // close stdin
        process.waitForProcessOutput(sout, serr) // forward stdout and stderr
        process.waitFor()

        if (process.exitValue() > 0 || serr.toString().contains(":") || sout.toString().contains(":")) {
            println "Error while extracting files from package.zip"
            System.exit(1);
        }

        // rename file
        try {
            zipFile.renameTo(new File("${baseDirectory.path}/processed_${packageZipFileName}"))
        } catch (Exception e) {
            println "Error while renaming the package.zip file"
            e.printStackTrace();
            System.exit(1);
        }

        println "Deployment package extracted successfully"
    }
}

static boolean isSecondVersion(File verFile) {
    FileReader fr = new FileReader(verFile);
    BufferedReader br = new BufferedReader(fr);
    boolean secondVersion = false;
    String splitStr;
    String[] words = null;
    String input = "<manifest type=\"MANIFEST_LIST\" version=\"v2_0\"";
    while ((splitStr = br.readLine()) != null) {
        words = splitStr.split(">");
        for (String word : words) {
            if (word.contains(input)) {
                secondVersion = true;
                break;
            }
        }
    }
    fr.close();
    return secondVersion;
}
