#!/bin/bash

# Creates a thread dump from a jboss instance

# Exit on any errors
set -e

function print_help {
    echo "Usage: $0 app-name namespace uuid"
    echo "Get a thread dump for a running application"

    echo "$0 $@" | logger -p local0.notice -t openshift_origin_threaddump
    exit 1
}

while getopts 'd' OPTION
do
    case $OPTION in
        d) set -x
        ;;
        ?) print_help
        ;;
    esac
done

[ $# -eq 3 ] || print_help

# Load the jboss_version and jboss_home settings
. `dirname $0`/jboss.version
cartridge_type="${jboss_version}"

source "/etc/openshift/node.conf"
source ${CARTRIDGE_BASE_PATH}/abstract/info/lib/util

setup_basic_hook "$1" $2 $3

source_if_exists $APP_HOME/.env/OPENSHIFT_GEAR_UUID
source_if_exists $APP_HOME/.env/OPENSHIFT_APP_UUID
if [ "$OPENSHIFT_GEAR_UUID" != "$OPENSHIFT_APP_UUID" ]
then
    client_error "The threaddump command is not supported on scalable applications."
    exit
fi

JBOSS_INSTANCE_DIR=$(get_cartridge_instance_dir "$cartridge_type")

#
# Get the thread dump
#
run_as_user "${CARTRIDGE_BASE_PATH}/${cartridge_type}/info/bin/app_ctl.sh threaddump"

client_result "Success"
client_result ""
client_result "The thread dump file will be available via: rhc tail $1 -f $cartridge_type/$cartridge_type/standalone/tmp/$cartridge_type.log -o '-n 250'"
