import com.urbancode.air.AirPluginTool
import com.urbancode.air.CommandHelper

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

def apTool = new AirPluginTool(args[0], args[1])
final def props = apTool.getStepProperties()

def ritInstallDir = props['installDir'];
println "ritInstallDir : " + ritInstallDir;
def ritProjectDir = props['projectDir'];
println "ritProjectDir : " + ritProjectDir;
def environment = props['environment'];
println "environment: " + environment;
def ritProject = props['ritProject'];
println "ritProject: " + ritProject;
def testResources = props['testResources'];
println "testResources: " + testResources;
def noResultsPublishers = props['noResultsPublishers'];
println "noResultsPublishers: " + noResultsPublishers;
def resultsPublishers = props['resultsPublishers'];
println "resultsPublishers: " + resultsPublishers;
def resultsServerLogging = props['resultsServerLogging'];
println "resultsServerLogging: " + resultsServerLogging;
def inputPropertyFile = props['inputPropertyFile'];
println "inputPropertyFile: " + inputPropertyFile;
def PLUGIN_HOME = System.getenv("PLUGIN_HOME");

def pluginHomeFile = new File(PLUGIN_HOME);
if (!pluginHomeFile.exists()) {
	throw new RuntimeException("Cannot get PLUGIN_HOME");
}

def libDir = new File(pluginHomeFile, "lib");
if (!libDir.exists()) {
	throw new RuntimeException("Cannot get lib directory!");
}

def ch = new CommandHelper(new File('.'))

try {

	// Build command
	def runTestsCmd = "RunTests"
	if (ritInstallDir) {
	  runTestsCmd = ritInstallDir + File.separator + runTestsCmd;
	}
	
	// Build args
	def args = [];
	args = [runTestsCmd, '-project', ritProjectDir + File.separator + ritProject, '-run', testResources, '-environment', environment];
	if ("true".equalsIgnoreCase(noResultsPublishers)) {
	  args << '-noResultsPublishers';
	}
	else if (resultsPublishers) {
	  arg = '-useResultsPublishers';
	  args << arg;
	  args << resultsPublishers;
	}
	    arg = '-resultsServerLogging';
	    args << arg;
	if (resultsServerLogging) {
	  args << resultsServerLogging;
	}
	else {
	  args << 'absolute';
	}	
	if (inputPropertyFile) {
	  arg = '-input';
	  args << arg;
	  args << inputPropertyFile;;
	}
		
	// Execute
	ch.runCommand("Running tests..", args);

}
catch (Exception e) {
    System.out.println("Error running tests!");
    e.printStackTrace();
    System.exit(1);
}