#!/bin/sh

######################### CONFIGURATION ######################################

PERL=perl

######################### CONFIGURATION ######################################

usage() {
  echo ""
  echo "Usage: $0 [conf_dir]"
  echo ""
}

for arg in "$@" 
do
  case "$arg" in
    -h | -help | --help | -\?)
      usage
      exit 0;;
    *)
      ;;
  esac
done

if [ $# -ne 0 ] && [ $# -ne 1 ]
then
  usage
  exit 1
fi


#
# detect TSI installation Directory
#
TSI_BIN=`dirname $0`

if [ "${TSI_BIN#/}" = "$TSI_BIN" ]
then
  if [ "$TSI_BIN" != "." ]
  then
    TSI_DIR="$(pwd)/$TSI_BIN"
  else
    TSI_DIR="$(pwd)"
  fi
else
  TSI_DIR=$TSI_BIN
fi

TSI_DIR="${TSI_DIR%/bin}"


# Detect configuration directory:

if [ $# -eq 1 ]
then
	TSI_CONF=$1
elif [ -n "$UNICORE_TSI" ]
then
	TSI_CONF=$UNICORE_TSI
else
	TSI_CONF="${TSI_DIR}/conf"
fi


# Sanity check. TSI_CONF must exist, be a directory and be x.

if [ ! -d $TSI_CONF ] 
then
	echo "TSI configuration directory $TSI_CONF is not a directory (or cannot be found)" 1>&2
	exit 1
fi

if [ ! -x  $TSI_CONF ] 
then 
	echo "Cannot execute TSI configuration directory $TSI_CONF" 1>&2
	exit 1
fi

#
# find tsi.properties file
#
if [ ! -r $TSI_CONF/tsi.properties ] 
then
	echo "The TSI configuration file $TSI_CONF/tsi.properties does not exist (or is not readable)." 1>&2
	exit 1
fi

TSI_PROPS=$TSI_CONF/tsi.properties


#
# PID file
#
PID_FILE="`perl -ne 'if(/^\s*tsi.pidfile\s*=\s*(\S+)/) {print $1}' $TSI_PROPS`"
if [ -z "$PID_FILE" ]; then
  PID_FILE=$TSI_CONF/LAST_TSI_PIDS
fi


#
# Look for TSI processes (shepherd and worker)
#
ppids=`cat $PID_FILE | sort -nr | xargs -n 10000`
if [ "$ppids" = "" ]; then
  $PERL -e '{printf STDERR "ERROR: empty $PID_FILE file\n"}'
  exit 1
fi

findpids="`echo $ppids | sed 's/ /|/g'`"

$PERL -e 'printf STDERR "  PID  PPID     USER    RUSER    GROUP   RGROUP COMMAND\n"'
ppids=`ps -eo pid,ppid,user,ruser,group,rgroup,args | sort -nr | $PERL -ne 'if(/^\s*('$findpids')\s+/) {printf STDERR "%s", $_; print $1." "}'`

allpids=""
while [ "$findpids" != "" ]; do
  pids=`ps -eo pid,ppid,user,ruser,group,rgroup,args | sort -nr | $PERL -ne 'if(/^\s*(\d+)\s+('$findpids')\s+/) {printf STDERR "%s", $_; print $1." "}'`
  allpids="$pids $allpids"
  findpids="`echo $pids | sed 's/ /|/g'`"
done

$PERL -e 'printf STDERR "Found pids "'
echo $allpids $ppids
