/*
 * Licensed Materials - Property of IBM Corp.
 * IBM UrbanCode Deploy
 * (c) Copyright IBM Corporation 2014, 2016. 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.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 containerSourceSnapshotAcronym = props['containerSourceSnapshotAcronym']
def containerTargetSnapshotAcronym = props['containerTargetSnapshotAcronym']
def containerAcronym = props['containerAcronym']

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

// Construct the target migration file path
def migrationPolicyFile = props['migrationPolicyFile']
if (!migrationPolicyFile) {
    migrationPolicyFile = containerAcronym + ".xml"
}
else if (!migrationPolicyFile.endsWith(".xml")) {
    println "The Migration file '${migrationPolicyFile}' must end with a .xml extension."
    System.exit(1)
}

// Does xml file exist? If so, delete it and get its full path.
def migrationPathString = WebSphereBPMHelper.removeFileReturnPath(migrationPolicyFile, workDir)


//////// Construct the BPMExtractMigrationPolicy Command ////////
def containerAcronymArgs = "-containerAcronym ${containerAcronym}"
def containerSourceSnapshotAcronymArgs = "-containerSourceSnapshotAcronym ${containerSourceSnapshotAcronym}"
def containerTargetSnapshotAcronymArgs = "-containerTargetSnapshotAcronym ${containerTargetSnapshotAcronym}"
def outputFileArgs = "-outputFile \"${migrationPathString}\""

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

// Check if migration policy was created
migrationFile = new File(migrationPathString)
if (!migrationFile.isFile()) {
    println "The Migration file '${migrationPolicyFile}' was not created."
    exitVal = 1
}

System.exit(exitVal)