/*
* Licensed Materials - Property of HCL
* UrbanCode Build
* (c) Copyright HCL Technologies Ltd. 2019. All Rights Reserved.
*/
import com.urbancode.air.AirPluginTool
import com.urbancode.air.CommandHelper

File workDir = new File('.').canonicalFile

AirPluginTool apTool = new AirPluginTool(this.args[0], this.args[1])
Properties props = apTool.getStepProperties()

String ucdAuthToken = props["job/ucdUserAuthToken"] ?: props["buildlife/ucdUserAuthToken"] ?: props['automation/authToken']

String ucdAgentHome = props["ucdAgentHome"]
File buztoolFile = new File(ucdAgentHome, "bin/buztool.sh")
if (!buztoolFile.exists()) {
    System.err.println("Unable to find Buztool at \"${buztoolFile.getPath()}\"")
}

String component = props["component"]
String versionName = props["versionName"]
boolean verbose = Boolean.parseBoolean(props["verbose"] as String)
String shiplistPath = props["shiplistPath"]
File shiplistFile = new File(shiplistPath)
if (!shiplistFile.exists()) {
    System.err.println("Unable to find shiplist at \"${shiplistPath}\"")
}

String outputFilePath = props["output"]
String type = props["type"]

// Build command args
List<String> cmdArgs = [buztoolFile.getPath(), "createzosversion"] as List<String>

cmdArgs.add("-c")
cmdArgs.add(component)

if (versionName) {
    cmdArgs.add("-v")
    cmdArgs.add(versionName)
}

cmdArgs.add("-s")
cmdArgs.add(shiplistPath)

if (ucdAuthToken) {
    cmdArgs.add("-to")
    cmdArgs.add(ucdAuthToken)
}

cmdArgs.add("-verb")
if (verbose) {
    cmdArgs.add("true")
}
else {
    cmdArgs.add("false")
}

if (outputFilePath) {
    File outputFile = new File(outputFilePath)
    if (!outputFile.isAbsolute()) {
        outputFile = new File(workDir.path, outputFilePath)
    }
    cmdArgs.add("-o")
    cmdArgs.add(outputFile.getPath())
}

if (!type) {
    type = "incremental"
}
cmdArgs.add("-t")
cmdArgs.add(type)

// Invoke Buztool
CommandHelper cmdHelper = new CommandHelper()
int returnCode = cmdHelper.runCommand("Invoking Buztool", cmdArgs.toArray())

if (returnCode != 0) {
    System.err.println("Return code indicated failure: $returnCode")
    System.exit(returnCode)
}