#!/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.*
import com.urbancode.air.securedata.Base64Codec;

final def workDir = new File('.').canonicalFile
final def apTool = new AirPluginTool(this.args[0], this.args[1]);
final def props = apTool.getStepProperties()
final CommandHelper cmdHelper = new CommandHelper(workDir);

final def scriptBody = props['scriptBody']
final def groovyHome = props['groovyHome']
String classPaths  = props['classPaths']?:""
final def apTEncKey = apTool.getEncKey();
def encKey = "";
if (apTEncKey != null) {
    encKey = apTEncKey;
}
assert groovyHome
cmdHelper.removeEnvironmentVariable("GROOVY_HOME")

def script = """
import com.urbancode.air.AirPluginTool;
import com.urbancode.air.securedata.Base64Codec;

final apTool = new AirPluginTool(args[0], args[1]);
final def inProps = apTool.getStepProperties("${encKey}");
final def outProps = new Properties();

addShutdownHook({
    outProps.each { key, value ->
        apTool.setOutputProperty(key, value);
    }
    apTool.setOutputProperties("${encKey}");
});

${scriptBody};
"""

List<String> classPathsToInclude = classPaths.split(",|\n")*.trim() - [""];
println("[Info] Externally supplied classPaths :" + classPathsToInclude);

File scriptFile = File.createTempFile("groovy_script_", ".groovy")
scriptFile.text = script

def PLUGIN_HOME= System.getenv("PLUGIN_HOME");
def libDir = new File(new File(PLUGIN_HOME), "lib");

def addClasspathElement = { current, newFile ->
    if (!current) {
        return newFile.absolutePath ;
    }
    else {
        return current + File.pathSeparator + newFile.absolutePath;
    }
}

try {
    def groovy = "${groovyHome}/bin/groovy"
    def classpath = null;
    classpath = addClasspathElement(classpath, new File("."));
    classpath = addClasspathElement(classpath, new File(PLUGIN_HOME, "classes"));
    classpath = addClasspathElement(classpath, new File(libDir,"CommonsUtil.jar"));
    classpath = addClasspathElement(classpath, new File(libDir,"securedata.jar"));
    classpath = addClasspathElement(classpath, new File(libDir,"jettison.jar"));
    classpath = addClasspathElement(classpath, new File(libDir,"commons-codec.jar"));

    //Adding external classpaths specified by user
    if(classPathsToInclude.size()>0) {
        classPathsToInclude.each{ cp ->
            File file = new File(cp);
            if(file.exists()) {
                classpath = addClasspathElement(classpath, file);
            }else {
                println("")
                throw new Exception("[Exception] classpath : " + cp + " - Not found" + "- Please enter valid classpath.");
            }
        }
    }

    if (apTool.isWindows) {
        groovy += ".bat"
    classpath = "\"${classpath}\"";
    }
    def command = [groovy, "-cp", classpath, scriptFile, args[0], args[1]]
    cmdHelper.runCommand("Running Groovy Script", command)
}
finally {
    scriptFile.delete()
}
