/*
 * 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 ch = new CommandHelper(new File("."))

final def props = apTool.getStepProperties()
final def isWindows = apTool.isWindows

final def workDir = new File('.').getCanonicalFile()
final def compName = new File(".").getCanonicalFile().name //this gets resolved to component name

def commandArgs = WebSphereBPMHelper.createCommandArgs(props, isWindows)

def containerSnapshotAcronym = props['containerSnapshotAcronym']
def containerTrackAcronym = props['containerTrackAcronym']
def containerAcronym = props['containerAcronym']
if (!containerAcronym) {
    containerAcronym = compName
}

containerAcronym = WebSphereBPMHelper.getContainerAcronym(containerAcronym, commandArgs)
containerSnapshotAcronym = WebSphereBPMHelper.getSnapshotTrackAcronym(containerSnapshotAcronym, containerAcronym, commandArgs)
containerTrackAcronym = WebSphereBPMHelper.getSnapshotTrackAcronym(containerTrackAcronym, containerAcronym, commandArgs)

def skipGovernance = props['skipGovernance']
def createOrigInvokeArgs = '[ -containerAcronym ' + containerAcronym + ' -containerSnapshotAcronym ' + containerSnapshotAcronym + ' -containerTrackAcronym ' + containerTrackAcronym
def extractInvokeArgs = new String(createOrigInvokeArgs)
if (!skipGovernance.equals("false")) {
    createOrigInvokeArgs = createOrigInvokeArgs + ' -skipGovernance ' + skipGovernance
}

def servers = props['servers']
def offlineServers = servers.split(",")
def timeout
try {
    timeout = Integer.parseInt(props['timeout']?:'0')
    if (timeout < 0) {
        throw new NumberFormatException()
    }
}
catch (NumberFormatException e) {
    println "[Error] Timeout found '${props['timeout']}'. Please specify a Timeout integer with value of 0 or greater."
    System.exit(1)
}

for (offlineServer in offlineServers) {
    def createInvokeArgs = createOrigInvokeArgs + ' -serverName ' + '"' + offlineServer + '"'
    def invoke = "AdminTask.BPMCreateOfflinePackage('" + createInvokeArgs + "]')"
    def retCode = WebSphereBPMHelper.invokeCommand(invoke, commandArgs, isWindows, ch)
    if (retCode == 0) {
        extractInvokeArgs = extractInvokeArgs + ' -serverName ' + '"' + offlineServer + '"'
        def packagePathString = workDir.toString() + File.separator + offlineServer + ".zip"
        packagePathString = packagePathString.replace('\\', '/')
        File packagedFile = new File(packagePathString)
        if (packagedFile.isFile()) {
            packagedFile.delete()
        }
        extractInvokeArgs = extractInvokeArgs + ' -outputFile ' + '"' + packagePathString + '"'

        int limit = timeout?3:1
        for (int i = 0; i < limit; i++) {
            // Workaround to ensure package is created in BPMCreateOfflinePackage
            if (timeout) {
                println "=========================================="
                println "[Ok] BPMCreateOfflinePackage attempt #${i} with a timeout of ${timeout} milliseconds."
                sleep(timeout)
            }
            invoke = "AdminTask.BPMExtractOfflinePackage('" + extractInvokeArgs + "]')"
            retCode = WebSphereBPMHelper.invokeCommand(invoke, commandArgs, isWindows, ch)

            if (timeout && (retCode == 0)) {
                break
            }
        }
        if (retCode != 0) {
            System.exit(retCode)
        }
    }
    else {
        System.exit(retCode)
    }
}
