final def workDir = new File('.').canonicalFile
final def props = new Properties();
final def inputPropsFile = new File(args[0]);
try {
    inputPropsStream = new FileInputStream(inputPropsFile);
    props.load(inputPropsStream);
}
catch (IOException e) {
    throw new RuntimeException(e);
}

def tomcatManagerUrl = props['tomcatManagerUrl'];
println "ManagerURL : " + tomcatManagerUrl;
def tomcatManagerUsername = props['tomcatUsername'];
println "ManagerUsername : " + tomcatManagerUsername;
def tomcatManagerPassword = props['tomcatPassword'];
def tomcatContext = props['tomcatContext'];
println "Tomcat context : " + tomcatContext;
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 catalinaJar = new File(libDir, "catalina-ant.jar");
if (!catalinaJar.exists()) {
    throw new RuntimeException("Cannot find cantalina-ant.jar!");
}

def ant = new AntBuilder();

try {
    ant.path(id:"tomcat.classpath") {
        pathelement(path:catalinaJar.getAbsolutePath());
    }
    ant.taskdef(name:"undeploy", classname:"org.apache.catalina.ant.UndeployTask", classpathref:"tomcat.classpath")
    ant.undeploy(url:"${tomcatManagerUrl}",
               username:"${tomcatManagerUsername}",
               password:"${tomcatManagerPassword}",
               path:"${tomcatContext}")
}
catch (Exception e) {
    System.out.println("Error deploying!");
    e.printStackTrace();
    System.exit(1);
}
