#!/bin/bash
#< Get active thread count for a JBoss instance

AWK="/usr/bin/awk"
BASENAME="/bin/basename"
CUT="/usr/bin/cut"
ECHO="/bin/echo"
GREP="/bin/grep"
HOSTNAME="/bin/hostname"
JAVA="/usr/local/java1.4/bin/java"
PS="/usr/bin/ps"
PTREE="/usr/bin/ptree"
UCB_PS="/usr/ucb/ps"

JBOSS_ROOT="/usr/local/jboss4"
JBOSS_BIN="${JBOSS_ROOT}/bin"
JBOSS_SERVER="${JBOSS_ROOT}/server"
TWIDDLE="${JBOSS_BIN}/twiddle.sh"
THISPROG=$( ${BASENAME} $0 )

PORT_MAP="instance-01 1199
instance-02 1299
instance-03 1399
instance-04 1499"

function print_error {
   ${ECHO} "Error: $@" >&2
}

function print_usage {
   ${ECHO} "Usage: ${THISPROG} -s <instance>"
}

function check_instance_exists {
   if [ ! -d "${JBOSS_SERVER}/${JBOSS_INSTANCE}" ]; then
      print_error "${JBOSS_INSTANCE} is not a valid JBoss instance"
      exit 1
   fi
}

function check_instance_running {
   if [ "${JBOSS_INSTANCE}" = "instance-02" ]; then
      PS_OUTPUT=$( ${UCB_PS} auwwwx | ${GREP} "${JBOSS_INSTANCE}" | ${GREP} "run\.sh" )
      if [ "${PS_OUTPUT}" = "" ]; then
         print_error "Instance ${JBOSS_INSTANCE} is not running"
         exit 1
      else
         PARENT_PID=$( ${ECHO} "${PS_OUTPUT}" | ${AWK} '{print $2}' )
         INSTANCE_PID=$( ${PTREE} ${PARENT_PID} | ${GREP} "${JAVA}" | ${AWK} '{print $1}' )
      fi
   else
      PS_OUTPUT=$( ${UCB_PS} auwwwx | ${GREP} "${JBOSS_INSTANCE}" | ${GREP} "${JAVA}" )
      if [ "${PS_OUTPUT}" = "" ]; then
         print_error "Instance ${JBOSS_INSTANCE} is not running"
         exit 1
      else
         INSTANCE_PID=$( ${ECHO} "${PS_OUTPUT}" | ${AWK} '{print $2}' )
      fi
   fi
}

function get_instance_port {
   JNP_PORT=$( ${ECHO} "${PORT_MAP}" | ${GREP} "^${JBOSS_INSTANCE} " | ${AWK} '{print $2}' )
   if [ "${JNP_PORT}" = "" ]; then
      print_error "JNP port not defined in port map"
      exit 1
   fi 
}

function get_information {
   TWIDOUT=$( ${TWIDDLE} --server=jnp://$( ${HOSTNAME} ):${JNP_PORT} get jboss.system:type=ServerInfo )
   THREAD_COUNT=$( ${ECHO} "${TWIDOUT}" | ${GREP} "ActiveThreadCount" | ${CUT} -d= -f2 )
   ${ECHO} "${JBOSS_INSTANCE}: ${THREAD_COUNT} active threads"
}

# argument processing
if [ "$#" -ne "2" ]; then
   print_usage && exit 1
else
   if [ "$1" != "-s" ]; then
      print_usage && exit 1
   else
      JBOSS_INSTANCE=$2
   fi
fi

check_instance_exists
check_instance_running
get_instance_port
get_information

exit 0