/*
* Licensed Materials - Property of IBM* and/or HCL**
* UrbanCode Deploy
* (c) Copyright IBM Corporation 2014, 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.plugin.websphere.commerce.WebSphereCommerceHelper;
import com.urbancode.air.AirPluginTool;
import com.urbancode.air.CommandHelper;

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

def execFile = props['execFile']
def antUtil = props['antUtil']
def antBuildFile = props['antBuildFile']
def targetEnv = props['targetEnv']
def exitVal = 0;

def deployCommand = []
try {
    if (!WebSphereCommerceHelper.isEmpty(execFile)) {
        if (isWindows && (!(execFile =~ /(?i)\.bat$/))) {
            execFile = execFile + ".bat"
        }
        execFile = WebSphereCommerceHelper.findFile(".", execFile)
        deployCommand.add(new File(execFile).getCanonicalPath())
    } else {
        if (isWindows && (!(antUtil =~ /(?i)\.bat$/))) {
            antUtil = antUtil + ".bat"
        }
        if (!(antBuildFile =~ /(?i)\.xml$/)) {
            antBuildFile = antBuildFile + ".xml"
        }

        antUtil = WebSphereCommerceHelper.findFile(".", antUtil)
        antBuildFile = WebSphereCommerceHelper.findFile(".", antBuildFile)

        deployCommand.add(new File(antUtil).getCanonicalPath())
        deployCommand.add("-buildfile")
        deployCommand.add(new File(antBuildFile).getCanonicalPath())
        deployCommand.add("-Dtarget.env=" + targetEnv)
    }

    println deployCommand.join(' ');
    if (isWindows) ch.addEnvironmentVariable("PROFILE_CONFIG_ACTION", "true");
    ch.runCommand("Deploying WebSphere Commerce customization", deployCommand);
}
catch (Exception e) {
    e.printStackTrace();
    exitVal=1;
}
System.exit(exitVal);
