#!/bin/sh

#
# Detect TSI
#
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}"


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 configuration directory:
# - first look for command line argument
# - then in environment ($UNICORE_TSI)
# - lastly use value from this file (current 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


pids=`$TSI_BIN/find_pids $TSI_CONF`
echo "$pids"

if [ "$pids" != "" ]; then
  echo ""
  echo kill -9 $pids
  kill -9 $pids

else
  echo "Nothing to kill"
fi

rm -f $PID_FILE
