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 rtcpServerURL = props['serverURL'];
println "rtcpServerURL : " + rtcpServerURL;
def domain = props['domain'];
println "domain: " + domain;
def baseEnvironment = props['baseEnvironment'];
println "baseEnvironment: " + baseEnvironment;
def description = props['description'];
println "description: " + description;
def PLUGIN_HOME = System.getenv("PLUGIN_HOME");
  
def newEnvironmentName;

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:"createEnvironment", classname:"com.ghc.ghTester.ant.CreateEnvironment", classpathref:"gh.classpath")

    ant.property(name:'newenvName', value:'null')
    ant.createEnvironment(serverURL:"${rtcpServerURL}",
          domain:"${domain}",
          baseEnvironment:"${baseEnvironment}",
		  description:"${description}",
          nameProperty:"newenvName",
          failureProperty: "taskFailed")
	
	if (ant.project.properties.taskFailed == "true")
	{
	  System.out.println("Create transient environment failed!");
	  System.exit(1);
	}
	else
	{
      newEnvironmentName = ant.project.properties.newenvName
      println "New transient envirionment created: " + newEnvironmentName 
	  
	  // Write new environment name to output properties file
	  apTool.setOutputProperty("environmentName", newEnvironmentName);
	  apTool.setOutputProperties();
	}
                
}
catch (Exception e) {
    System.out.println("Error creating transient environment!");
    e.printStackTrace();
    System.exit(1);
}

         
