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

import org.apache.tools.ant.DefaultLogger

import com.urbancode.air.AirPluginTool

def apTool = new AirPluginTool(this.args[0], this.args[1]);
def props = apTool.getStepProperties();

def expectedStatus = props['expectedStatus'];
def tomcatManagerUrl = props['tomcatManagerUrl'];
def tomcatManagerUsername = props['tomcatUsername'];
def tomcatManagerPassword = props['tomcatPassword'];
def tomcatApplication = props['tomcatApplication'].trim();
def PLUGIN_HOME = System.getenv("PLUGIN_HOME");

def found = false;
def byteStream = new ByteArrayOutputStream();
def printStream = new PrintStream(byteStream);

// Assure that PLUGIN_HOME is set
if (!PLUGIN_HOME) {
    throw new RuntimeException("Environment variable PLUGIN_HOME is not set!");
}

// Assure that the catalina-ant.jar is reachable
def pluginHomeFile = new File(PLUGIN_HOME);
if (!pluginHomeFile.exists() || !pluginHomeFile.isDirectory()) {
    throw new RuntimeException("The PLUGIN_HOME directory is missing from your server directory!");
}

def libDir = new File(pluginHomeFile, "lib");
if (!libDir.exists() || !libDir.isDirectory()) {
    throw new RuntimeException("The directory PLUGIN_HOME/lib is missing from your PLUGIN_HOME directory!");
}

def catalinaJar = new File(libDir, "catalina-ant.jar");
if (!catalinaJar.exists() || !catalinaJar.isFile()) {
    throw new RuntimeException("The file PLUGIN_HOME/lib/catalina-ant.jar is missing from your PLUGIN_HOME directory!");
}

println "ManagerURL : " + props['tomcatManagerUrl'];
println "ManagerUsername : " + props['tomcatUsername'];

// Create AntBuilder and redirect output to stream in order to parse before printing
def ant = new AntBuilder();
ant.project.buildListeners.each{
    if (it instanceof  DefaultLogger) {
        it.outputPrintStream = printStream;
        it.errorPrintStream = printStream;
    }
}

    ant.path(id:"tomcat.classpath") {
        pathelement(path:catalinaJar.getAbsolutePath());
    }
    ant.taskdef(name:"list", classname:"org.apache.catalina.ant.ListTask", classpathref:"tomcat.classpath");

    ant.list(url:"${tomcatManagerUrl}",
            username:"${tomcatManagerUsername}",
            password:"${tomcatManagerPassword}");

    def outputString = byteStream.toString();

    // Parse through task output, find the line that correlates to the correct application, print the status and set an output property
    if (outputString.contains(tomcatApplication)) {
        def values = outputString.tokenize("\n");
        for(String row: values) {
            if (row.contains("/") && row.contains(":") && row.contains(tomcatApplication)) {
                // Make sure the application name matches a deployed application, as opposed to just part of the status string
                if (row.substring(row.indexOf('/'), row.indexOf(':')).equals(tomcatApplication)) {
                    def status = ((row.split(":"))[1].split(":"))[0];
                    System.out.println("Status of application with path ${tomcatApplication}: ${status}");
                    found = true;
                    System.out.println("Setting output property 'applicationStatus' to ${status}");
                    apTool.setOutputProperty("applicationStatus", status);
                    // If the status does not match the expected status, fail
                    if (status != expectedStatus) {
                        System.out.println("Application's status does not match expected status of ${expectedStatus}. Exiting process.");
                        System.exit(1);
                    }
                }
            }
        }
        apTool.storeOutputProperties();
    }
    if (found == false) {
        System.out.println("Application with path ${tomcatApplication} not found. Exiting process.");
        System.exit(1);
    }