#!/bin/bash

# Creates a thread dump from a ruby-1.9 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

source "/etc/openshift/node.conf"
source ${CARTRIDGE_BASE_PATH}/abstract/info/lib/util
cartridge_type="ruby-1.9"

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

#
# Get the thread dump
#

result=`run_as_user "$CARTRIDGE_BASE_PATH/ruby-1.9/info/bin/threaddump.sh $1 $3"`

if [ "$result" = "" ]; then
    DATE=`date -u '+%Y%m%d'`
    client_result "Success"
    client_result ""
    # note bz 923405/921537 for why log file name is not more specific
    client_result "The thread dump file will be available via: rhc tail ${application} -f ${cartridge_type}/logs/error_log-$DATE-* -o '-n 250'"
else
    client_result " $result"
fi

