/*
* 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 com.urbancode.air.AirPluginTool

final def workDir = new File('.').canonicalFile
def pluginTool = new AirPluginTool(args[0], args[1])
final def props = pluginTool.getStepProperties()
def env = System.getenv().collect{it.key + '=' + it.value}

def launcher = props['launcherLocation']
def options = props['options']
def hostname = props['hostname']?:'localhost'
def port = props['port'] == "" ? null : props['port'].toInteger()
def timeout = props['timeout'] == "" ? null : props['timeout'].toInteger()
def catalinaHome = props['catalinaHome']
def catalinaBase = props['catalinaBase']
def javaHome = props['javaHome']

println "Shutdown script: $launcher"
println "Shutdown options: ${options?.split('\n')?.collect {it}}"
println "Timeout: ${timeout?:''}"
println "Hostname: ${hostname?:''}"
println "Port: ${port?:''}"
println "Catalina Base: ${catalinaBase?:''}"
println "Catalina Home: ${catalinaHome?:''}"
println "Java Home: ${javaHome?:''}"

if (timeout && !port) {
    println "Port is required when timeout is specified"
    System.exit 1
}

def cmdArgs = [launcher];
if (options) {
    for (String option : options.split('\n')) {
        cmdArgs << option.trim();
    }
}
if (javaHome) {
    env << 'JAVA_HOME' + '=' + javaHome
}
if (catalinaBase) {
    env << 'CATALINA_BASE' + '=' + catalinaBase
}
if (catalinaHome) {
    env << 'CATALINA_HOME' + '=' + catalinaHome
}

if (port && timeout) {
    println 'Check if Tomcat is already running...'
    try {
        def socket = new Socket(hostname, port)
        try {
            socket.close()
        }
        catch (Exception e) {}
        println 'running - shutting down...'
        println "Executing " + cmdArgs.join(' ')
        def proc = cmdArgs.execute(env as String[], workDir)
        proc.waitForProcessOutput(System.out, System.out);
        proc.waitFor();
        if (proc.exitValue() != 0) {
            throw new RuntimeException("Process Failed!");
        }

        def endTime = System.currentTimeMillis() + (timeout * 1000)
        def done = false
        println 'Waiting for Tomcat shutdown process to complete...'

        while (!done && System.currentTimeMillis() < endTime) {
            try {
                socket = new Socket(hostname, port)
                try {
                    socket.close()
                }
                catch (Exception e) {}
                try {
                    sleep(1000)
                }
                catch (InterruptedException ie) {
                    println 'Sleep interrupted!'
                    System.exit 1
                }
            }
            catch (UnknownHostException uhee) {
                println uhee.message
                System.exit 1
            }
            catch (IllegalArgumentException iaee) {
                println iaee.message
                System.exit 1
            }
            catch (ConnectException cee) {
                done = true
            }
        }

        if (done) {
            println 'done.'
        }
        else {
            println 'failed - instance did not shut down in alloted time.'
            System.exit 1
        }
    }
    catch (UnknownHostException uhe) {
        println uhe.message
        System.exit 1
    }
    catch (IllegalArgumentException iae) {
        println iae.message
        System.exit 1
    }
    catch (ConnectException ce) {
        println 'not running - done'
    }
}
else {
    println "Executing " + cmdArgs.join(' ')
    def proc = cmdArgs.execute(env as String[], workDir)
    proc.waitForProcessOutput(System.out, System.out);
    proc.waitFor();
    if (proc.exitValue() != 0) {
        throw new RuntimeException("Process Failed!");
    }
    println 'Timeout and/or port not specified so not waiting for Tomcat shutdown process to complete.'
}

System.exit 0
