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;
 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:"stopScenario", classname:"com.ghc.ghTester.ant.StopScenario", classpathref:"gh.classpath")
	
	// Required args
	def stopScenarioArgs = [serverURL:"${rtcpServerURL}",
            name:"${scenarioName}",
            domain:"${domain}",
            environment:"${environment}",
            failureProperty: "taskFailed"]

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

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

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