/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Build
* IBM UrbanCode Deploy
* IBM UrbanCode Release
* IBM AnthillPro
* (c) Copyright IBM Corporation 2002, 2016. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*/
import com.urbancode.air.AirPluginTool

final AirPluginTool airPluginTool = new AirPluginTool(this.args[0], this.args[1])
final Properties props = airPluginTool.getStepProperties()

final def workDir = new File('.').canonicalFile

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);
}
