/*
 * Licensed Materials - Property of IBM* and/or HCL**
 * UrbanCode Deploy
 * (c) Copyright IBM Corporation 2011, 2017. All Rights Reserved.
 * (c) Copyright HCL Technologies Ltd. 2019. 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.AirPluginTool;
import com.urbancode.air.CommandHelper;
import com.urbancode.air.plugin.websphere.bpm.WebSphereBPMHelper;

//////////////////////MAIN////////////////////////
final def apTool = new AirPluginTool(this.args[0], this.args[1])
final def workDir = new File('.').canonicalFile
final def ch = new CommandHelper(workDir)
final def props = apTool.getStepProperties()
final def isWindows = apTool.isWindows
final def compName = workDir.getCanonicalFile().name //this gets resolved to component name

def commandArgs = WebSphereBPMHelper.createCommandArgs(props, isWindows)

////////////// BPM Command Arguments /////////////
def containerSnapshotAcronym = props['containerSnapshotAcronym']
def containerTrackAcronym = props['containerTrackAcronym']
def containerAcronym = props['containerAcronym']

// Retrieve snapshot acronym if name is given
containerAcronym = WebSphereBPMHelper.getContainerAcronym(containerAcronym, commandArgs)
containerSnapshotAcronym = WebSphereBPMHelper.getSnapshotTrackAcronym(containerSnapshotAcronym, containerAcronym, commandArgs)
containerTrackAcronym = WebSphereBPMHelper.getSnapshotTrackAcronym(containerTrackAcronym, containerAcronym, commandArgs)

// Construct the target package file path
def packageZipFile = props['packageZipFile']
if (!packageZipFile) {
    packageZipFile = containerAcronym + ".zip"
}
else if (!packageZipFile.endsWith(".zip")) {
    println "The Package Zip file '${packageZipFile}' must end with a .zip extension."
    System.exit(1)
}

// Does zip file exist? If so, delete it and get its full path.
String packagePath = WebSphereBPMHelper.removeFileReturnPath(packageZipFile, workDir)

//////// Construct the BPMExportInstallPackage Command ////////
def containerAcronymArgs = "-containerAcronym ${containerAcronym}"
def containerSnapshotAcronymArgs = "-containerSnapshotAcronym ${containerSnapshotAcronym}"
def containerTrackAcronymArgs = "-containerTrackAcronym ${containerTrackAcronym}"
def outputFileArgs = "-outputFile \"${packagePath}\""

def invoke = "AdminTask.BPMExportInstallPackage('[${containerAcronymArgs} " +
            "${containerSnapshotAcronymArgs} ${containerTrackAcronymArgs} ${outputFileArgs}]')"
def exitVal = WebSphereBPMHelper.invokeCommand(invoke, commandArgs, isWindows, ch)

// Check if package zip was created
packageFile = new File(packagePath)
if (!packageFile.isFile()) {
    println "The Package Zip file '${packageZipFile}' was not created."
    exitVal = 1
}

System.exit(exitVal)