import com.urbancode.air.AirPluginTool
final def workDir = new File('.').canonicalFile

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

def rtcpServerURL = props['serverURL'];
println "rtcpServerURL : " + rtcpServerURL;
def domain = props['domain'];
println "domain: " + domain;
def environment = props['environment'];
println "environment: " + environment;
def scenarioName = props['scenarioname'];
println "Scenario name: " + scenarioName;
def username = props['username'];
println "username: " + username;
def owner = props['owner'];
println "owner: " + owner;
def force = props['force'];
println "force: " + force;
def stopStubs = props['stopStubs'];
println "stopStubs: " + stopStubs;
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 ant = new AntBuilder();

try {
    ant.path(id:"gh.classpath") {
      fileset(dir:libDir) {
          include(name:"*.jar")
      }
    }
    
    ant.taskdef(name:"startScenario", classname:"com.ghc.ghTester.ant.StartScenario", classpathref:"gh.classpath")
	
	// Required args
	def startScenarioArgs = [serverURL:"${rtcpServerURL}",
            name:"${scenarioName}",
            domain:"${domain}",
            environment:"${environment}",
            failureProperty: "taskFailed"]

	// Optional args
	if (owner != null && owner.trim().length() > 0) {
		startScenarioArgs.put("owner", "${owner}")
	}		
	if (username != null && username.trim().length() > 0) {
		startScenarioArgs.put("username", "${username}")
	}		
	if (force != null && force.trim().length() > 0) {
		startScenarioArgs.put("force", "${force}")
	}
	if (stopStubs != null && force.trim().length() > 0) {
		startScenarioArgs.put("stopStubs", "${stopStubs}")
	}

	// Execute task
    ant.startScenario(startScenarioArgs)
           
    
    if (ant.project.properties.taskFailed == "true")
    {
      System.out.println("startScenario task failed!");
      System.exit(1);
    }
    else
    {
      System.out.println("Successfully started scenario: " + scenarioName);	
    }

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