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 stubName = props['stubname'];
println "Stub name: " + stubName;
def stubVersion = props['version'];
println "Stub version: " + stubVersion;
def component = props['component'];
println "Component: " + component;
def operation = props['operation'];
println "Operation: " + operation;
def username = props['username'];
println "username: " + username;
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:"stopStub", classname:"com.ghc.ghTester.ant.StopStub", classpathref:"gh.classpath")

	// Required args
	def stopStubArgs = [serverURL:"${rtcpServerURL}",
			name:"${stubName}",
			domain:"${domain}",
			environment:"${environment}",
			failureProperty: "taskFailed"]

	// Optional args
	if (component != null && component.trim().length() > 0) {
		stopStubArgs.put("component", "${component}")
	}
	if (operation != null && operation.trim().length() > 0) {
		stopStubArgs.put("operation", "${operation}")
	}
	if (username != null && username.trim().length() > 0) {
		stopStubArgs.put("username", "${username}")
	}
	if (stubVersion != null && stubVersion.trim().length() > 0) {
		stopStubArgs.put("version", "${stubVersion}")
	}
	
	// Execute task
	ant.stopStub(stopStubArgs)
    
    if (ant.project.properties.taskFailed == "true")
    {
      System.out.println("stopStub task failed!");
      System.exit(1);
    }
    else
    {
      System.out.println("Successfully stopped stub: " + stubName);
    }
  
  }
  catch (Exception e) {
      System.out.println("Error stopping stub!");
      e.printStackTrace();
      System.exit(1);
  }
