#! /bin/sh
#
# Collect each T-HA daemon memory usage and statistics and dump it on
# stdout. Data is collected by sending the "dcon", "stats" and "time"
# commands with -R<file> option to the T-HA debug thread of each
# daemon in parallel and then waiting for the each daemon to output
# data in the specified file.
#
# Note that the command completion is detected by looking for the
# "ElapsedTime" phrase on the last line, which is printed in response
# to the "time" command.
#
# Usage: thainfo [-s]
#

FILES=
SUMMARY=0
CLEAR=0
for f in $*
do
	case $f in
	-clear) CLEAR=1; shift;;
	-s*)	SUMMARY=1; shift;;
	-*)		echo "Unknown option: $f ... ignored"; shift;;
	*)		FILE=`/bin/ls /tmp/tha/hadebug.* | grep $f`
			if [ $? -eq 0 ]
			then FILES=`echo $FILES $FILE | sort -u`
			else echo "Can't find /tmp/tha/hadebug.* FIFO for $f"; exit 1
			fi
			shift;;
	esac
done

if [ "z$FILES" == "z" ]
then FILES=`/bin/ls /tmp/tha/hadebug.*`
fi

if [ $CLEAR -eq 1 ]
	then
	for f in $FILES
	do
		echo "stat -clear" >  $f &
	done
	echo "Cleared THA stats";
	exit 0
fi

i=0
for f in $FILES
do
	LOGFILE=`echo $f | sed 's,/tmp/tha/hadebug,/tmp/tha/halog,'`
	INFOFILE=`echo $f | sed 's,/tmp/tha/hadebug,/tmp/tha/hainfo,'`
	if [ -f $INFOFILE ]
		then
		rm -f $INFOFILE
	fi
	if [ $SUMMARY -eq 0 ]
	then
		echo "dcon -R$INFOFILE; stat -R$INFOFILE; time -R$INFOFILE" >  $f &
	else
		echo "dcon -R$INFOFILE; time -R$INFOFILE" >  $f &
	fi
	i=`expr $i + 1`
done

# Wait for few seconds for everyone to start processing the command
sleep 2

i=0
for f in $FILES
do
	INFOFILE=`echo $f | sed 's,/tmp/tha/hadebug,/tmp/tha/hainfo,'`
	if [ -f $INFOFILE ]
	then
		LAST=`tail -1 $INFOFILE | awk '{print $1}'`
		if [ "z$LAST" != "zElapsedTime:" ]
		then
			sleep 3
		fi
		echo "---- THA info from $INFOFILE  ----"
		cat $INFOFILE
		echo
		rm $INFOFILE
	fi
		i=`expr $i + 1`
done
