#!/bin/bash

# This file is part of IKR SimTree
# (C) 2009-2014 University of Stuttgart, IKR

# Hook file template which controls a running process (Linux specific)

# %%HOOK_FILE_SOURCE_COMMENT%%

### Parameters

# The pid of the controlled process
PROC_ID="%%PROC_ID%%"

# The command to execute
COMMAND="%%COMMAND%%"

############
# Make a status message

StatusMessage()
{
  echo "[#SimTreeControl#PS#${COMMAND}#] $1"
}

############
# Build a list of all direct/indirect children of proc
#  $1  pid of proc
#  list is echoed to stdout

BuildProcessList()
{
  local pslist

  # $1  pid to find children for, echo the children
  iBuild()
  {
    echo -e "$pslist" | while read pid ppid; do
      if [ "$ppid" = "$1" ]; then
        echo -n "${pid},"
        iBuild "$pid"
      fi
    done
  }

  # create list from ps
    pslist="`ps -e -o pid,ppid --no-headers`"
  # recur search (no double %, hook replacement)
    local p="${1},`iBuild $1`"
    echo ${p%,}
}

############
# Main

# build list of pids of all children of PROC_ID including PROC_ID
PROC_LIST="`BuildProcessList $PROC_ID`"

case "$COMMAND" in
  STAT ) # return process status
    StatusMessage "On host $HOSTNAME"
    ps -p $PROC_LIST -o time,pcpu,vsz,comm | while read line; do
      StatusMessage "  $line"
    done
    ;;
  KILL ) # kill process family (process and all ot its children), return one line of answer
    IFS=,
    for p in $PROC_LIST; do
      kill $p
    done
    unset IFS
    StatusMessage "Killed processes $PROC_LIST (Host $HOSTNAME)"
    ;;
  *)
    exit -1
    ;;
esac

# terminate message  
  StatusMessage

# end
  exit 0

# End of file
