/*
 * Licensed Materials - Property of IBM Corp.
 * IBM UrbanCode Deploy
 * (c) Copyright IBM Corporation 2015. All Rights Reserved.
 *
 * U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
 * GSA ADP Schedule Contract with IBM Corp.
 */
import com.urbancode.air.CommandHelper
import com.urbancode.air.AirPluginTool

final def ch = new CommandHelper(new File('.').canonicalFile)
final def apTool = new AirPluginTool(this.args[1], this.args[2])
final def props = apTool.getStepProperties()
final def isWindows = apTool.isWindows

def jarFolder = props['jarFolder']

def PLUGIN_HOME = System.getenv("PLUGIN_HOME")
def cmdArgs = []
File libraryDir

try {
    libraryDir = new File(jarFolder)
}
catch (FileNotFoundException ex) {
    println("File path: ${jarFolder} does not exist on the file system.")
    System.exit(1)
}

def stepExe = PLUGIN_HOME + File.separator + args[0]    //groovy script being run
def classpath = PLUGIN_HOME + File.separator + "classes" + File.pathSeparator

def pluginHomeJars = ["jettison-1.1.jar", "axis-jaxrpc-1.4.jar", "axis-1.4.jar", "commons-discovery-0.2.jar", "javamail-1.4.1.jar"]
def cognosExcludes = ["cognos-axis.jar", "jaxrpc.jar", "axis.jar"] // conflicting jar files

for (def jar : pluginHomeJars) {
    classpath += PLUGIN_HOME + File.separator + "lib" + File.separator + jar + File.pathSeparator
}

//include required jar files in the Cognos java library directory
libraryDir.eachFileRecurse() {
    if (it.isFile() && it.name.endsWith(".jar")) {
        if (!pluginHomeJars.contains(it.name) && !cognosExcludes.contains(it.name)) {
            classpath += "${it}${File.pathSeparator}"
        }
    }
}

def groovyHome = System.getProperty("groovy.home")
def groovyExe = groovyHome + File.separator + "bin" + File.separator + "groovy"

if (isWindows) {
    groovyExe += ".bat"
}

cmdArgs << groovyExe
cmdArgs << "-cp"
cmdArgs << classpath
cmdArgs << stepExe
cmdArgs << args[1]
cmdArgs << args[2]

ch.runCommand(cmdArgs.join(' '), cmdArgs)