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 warFileName = props['warFile'];
println "War File : " + warFileName;
def configFile = props['configFile'];
println "Context XML: " + configFile;
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();
File warFile = new File(warFileName);
if (!warFile.exists()) {
    throw new Exception("War file does not exist!");
}

try {
    ant.path(id:"tomcat.classpath") {
        pathelement(path:catalinaJar.getAbsolutePath());
    }
    ant.taskdef(name:"deploy", classname:"org.apache.catalina.ant.DeployTask", classpathref:"tomcat.classpath")
    if (configFile != null && configFile.trim().length() > 0) {
        ant.deploy(url:"${tomcatManagerUrl}",
                username:"${tomcatManagerUsername}",
                password:"${tomcatManagerPassword}",
                path:"${tomcatContext}",
                localWar:"${warFileName}",
                config:"${configFile}")
        
    }
    else {
        ant.deploy(url:"${tomcatManagerUrl}",
                username:"${tomcatManagerUsername}",
                password:"${tomcatManagerPassword}",
                path:"${tomcatContext}",
                war:"${warFileName}")
    }
}
catch (Exception e) {
    System.out.println("Error deploying!");
    e.printStackTrace();
    System.exit(1);
}
