#!/bin/bash
#< Get JBoss thread count as a count of LWPs

# Thread count can be gleaned through twiddle - but twiddle is slowwwww so I avoid it where possible

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

JBOSS_ROOT="/usr/local/jboss4"
JBOSS_SERVER="${JBOSS_ROOT}/server"
THISPROG=$( ${BASENAME} $0 )

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_thread_count {
   THREAD_COUNT=$( ${PS} -L -p ${INSTANCE_PID} | ${WC} -l )
   # "remove" header...
   (( THREAD_COUNT = THREAD_COUNT - 1 ))
   ${ECHO} "${JBOSS_INSTANCE}: ${THREAD_COUNT} threads running"
}

# 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_thread_count

exit 0