/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Build
* (c) Copyright IBM Corporation 2017. 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

def apTool = new AirPluginTool(this.args[0], this.args[1])
def stepProps = apTool.getStepProperties()

// commandHelper
final def workDir = new File('.').canonicalFile
def commandHelper = new CommandHelper(workDir);
//------------------------------------------------------------------------------
// PARSE PROPERTIES
//------------------------------------------------------------------------------

final String osName = System.getProperty('os.name').toLowerCase(Locale.US)
final boolean windows = (osName =~ /windows/)
final String mainClassName = "cucumber.api.cli.Main"

def tags                        = stepProps['tags']
def name                        = stepProps['name']
def features                    = stepProps['features']
def step_definitions            = stepProps['step_definitions']
def javaHome                    = stepProps['javaHome']
def classpath                   = stepProps['javaClasspath']
def pluginType                  = stepProps['plugin']

def dryRun                      = Boolean.valueOf(stepProps['dryRun'])
def strict                      = Boolean.valueOf(stepProps['strict'])

//
// Validation
//
assert !workDir.isFile() : "Working directory ${workDir} is a file!"

// ensure work-dir exists
workDir.mkdirs()

//
// Build Command Line
//
def commandLine = []

def javaPath = "java"
if (javaHome) {
    if (windows) {
        javaPath = javaHome + "\\bin\\java.exe"
    }
    else {
        javaPath = javaHome + "/bin/java"
    }
}

commandLine << javaPath

if (classpath) {
    commandLine << "-cp"
    commandLine << classpath
}

commandLine << mainClassName

if (pluginType) {
    commandLine << "-p"
    commandLine << pluginType
}

commandLine << "-g"
commandLine << step_definitions
commandLine << features

if (tags) {
    commandLine << '-t'
    commandLine << tags
}

if (name) {
    commandLine << '-n'
    commandLine << name
}

if (dryRun) {
    commandLine << '-d'
}

if (strict) {
    commandLine << '-s'
}

commandHelper.runCommand('Executing Cucumber CLI', commandLine);

//write the output properties to the file
apTool.storeOutputProperties()

