#!/bin/bash
set -e

source $OPENSHIFT_CARTRIDGE_SDK_BASH
source ${OPENSHIFT_JBOSSEWS_DIR}/bin/util

if ! [ $# -eq 1 ]
then
    echo "Usage: \$0 [start|restart|graceful|graceful-stop|stop|threaddump]"
    exit 1
fi

source ${OPENSHIFT_JBOSSEWS_DIR}/bin/util

JBOSS_PID_FILE="${OPENSHIFT_JBOSSEWS_DIR}/run/jboss.pid"

# Kill the process given by $1 and its children
killtree() {
    local _pid=$1
    for _child in $(ps -o pid --no-headers --ppid ${_pid}); do
        killtree ${_child}
    done
    echo kill -9 ${_pid}
    kill -9 ${_pid}
}

# Check if the jbossas process is running
isrunning() {
    # Check for running app
    if [ -f "$JBOSS_PID_FILE" ]; then
      jbpid=$(cat $JBOSS_PID_FILE);
      running=`/bin/ps --no-headers --pid $jbpid`
      if test -n "$running";
      then
        return 0
      fi
    fi
    # not running
    return 1
}

# Check if the server http port is up
function ishttpup() {
    let count=0
    while [ ${count} -lt 64 ]
    do
        if /usr/sbin/lsof -P -n -i "@${OPENSHIFT_JBOSSEWS_IP}:${OPENSHIFT_JBOSSEWS_HTTP_PORT}" | grep "(LISTEN)" > /dev/null; then
            echo "Found ${OPENSHIFT_JBOSSEWS_IP}:${OPENSHIFT_JBOSSEWS_HTTP_PORT} listening port"
            return 0
        fi
        let count=${count}+1
        sleep 2
    done
    return 1
}

function start_app() {
    # Check for running app
    if isrunning; then
        echo "The jbossews cartridge is already running" 1>&2
    else
        echo "Starting jbossews cartridge"
        # Start
        export CATALINA_HOME=$OPENSHIFT_JBOSSEWS_DIR
        export CATALINA_BASE=$OPENSHIFT_JBOSSEWS_DIR
        export CATALINA_TMPDIR=${OPENSHIFT_JBOSSEWS_DIR}/tmp

        ${OPENSHIFT_JBOSSEWS_DIR}/bin/tomcat start > ${OPENSHIFT_JBOSSEWS_DIR}/logs/jbossews.log 2>&1 &
        PROCESS_ID=$!

        echo $PROCESS_ID > $JBOSS_PID_FILE
        if ! ishttpup; then
            echo "Timed out waiting for http listening port"
            exit 1
        fi
    fi
}

function stop_app() {
    if ! isrunning; then
        echo "The jbossews cartridge is already stopped" 1>&2
    elif [ -f "$JBOSS_PID_FILE" ]; then
        echo "Stopping jbossews cartridge"
        pid=$(cat $JBOSS_PID_FILE);
        echo "Sending SIGTERM to jboss:$pid ..." 1>&2
        killtree $pid
    else 
        echo "Failed to locate JBOSS PID File" 1>&2
    fi
}

function threaddump() {
    if ! isrunning; then
        echo "The jbossews cartridge is stopped"
        exit 1
    elif [ -f "$JBOSS_PID_FILE" ]; then
        pid=$(cat $JBOSS_PID_FILE);
        java_pid=`ps h --ppid $pid -o '%p'`
        kill -3 $java_pid
        client_result "Success"
        client_result ""
        client_result "The thread dump file will be available via: rhc tail $OPENSHIFT_APP_NAME -f */logs/catalina.out -o '-n 250'"
    else 
        echo "Failed to locate JBOSS PID File"
    fi
}

# Clean up any log files
function tidy() {
  client_message "Emptying log dir: $OPENSHIFT_JBOSSEWS_LOG_DIR"
  shopt -s dotglob
  rm -rf $OPENSHIFT_JBOSSEWS_LOG_DIR/*
  rm -rf $OPENSHIFT_JBOSSEWS_DIR/tmp/*
}

# Reconstruct JAVA_HOME and PATH based on the current version/marker selection
function update_configuration {
    export_java_home
    reinstall_path
}

case "$1" in
    start)
        start_app
        exit 0
    ;;
    graceful-stop|stop)
        stop_app
        exit 0
    ;;
    restart|graceful)
        stop_app
        start_app
        exit 0
    ;;
    threaddump)
        threaddump
        exit 0
    ;;
    tidy)
        tidy
        exit 0
    ;;
    status)
        if ! isrunning; then
            client_result "The application is either stopped or inaccessible"
            exit 0
        fi

        client_result "The jbossews cartridge is running."
        exit 0
    ;;
    build)
        ${OPENSHIFT_JBOSSEWS_DIR}/bin/build
        exit 0
    ;;
    deploy)
        ${OPENSHIFT_JBOSSEWS_DIR}/bin/deploy
        exit 0
    ;;
    update-configuration)
        update_configuration
        exit 0
    ;;
esac
