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 environment = props['environmentName'];
println "environment: " + environment;
def tagsPropertyFile = props['tagsPropertyFile'];
println "tagsPropertyFile: " + tagsPropertyFile;
def updateProps = props['updateProps'];
println "updateProps: " + updateProps;
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")
      }
    }
 
    if (tagsPropertyFile?.trim().size() == 0) {
      if (updateProps?.trim().size() > 0 ) {
        def propFile = new File(workDir, "update_env_tags.properties")
        tagsPropertyFile = propFile.canonicalPath  
        ant.propertyfile(file: tagsPropertyFile) {
          updateProps?.trim().split('\n').each {
            def index = it?.trim().indexOf('=')
            if (it && index != -1) {
              entry(key:it.trim().substring(0, index),
                  value: it.trim().substring(index + 1),
                  operation: '=')
            }
          }
        }
      }
      else {
        System.out.println("Must specify either updateProperties or tagsPropertyFile");
        System.exit(1);
      }
    }
    
    ant.taskdef(name:"updateEnvironment", classname:"com.ghc.ghTester.ant.UpdateEnvironment", classpathref:"gh.classpath")
      
    ant.updateEnvironment(serverURL:"${rtcpServerURL}",
          domain:"${domain}",
          environment:"${environment}",
          tagsPropertyFile:"${tagsPropertyFile}",
		  username:"${username}",
          failureProperty: "taskFailed")
	
	if (ant.project.properties.taskFailed == "true")
	{
	  System.out.println("Update environment failed!");
	  System.exit(1);
	}
	else
	{
	  println "Updated environment: " + environment
	}
          
  }
  catch (Exception e) {
    System.out.println("Error updating environment!");
    e.printStackTrace();
    System.exit(1);
  }
  

