#! /bin/bash
cyflexlogevent -t generic -m 1 -m "script" -m "$0" 

# This is a generic script to stop a running external data manager
# application.  Instances of the external data manager check for the
# existence of a file (known as a "stop file") as a signal that they
# should terminate.  This script is built around that feature.
#
# The "stop file" will be created and then this waits for the
# application to terminate normally.  If it has not terminated in a
# suitable amount of time, the application is killed.
#
# Usage: /cyflex/cmds/stop_loading <PID> <STOP_FILE> <TOTAL_WAIT> <RETRY>
#
# Arguments - All arguments are required.
#    PID - Process id of task to be terminated.
#    STOP_FILE - The file that the external data manager task should
#        monitor to see if it is to terminate.
#    TOTAL_WAIT - The total time in seconds that this task will wait
#        before giving up on the running task to exit gracefully.
#        If it hasn't terminated after this time, it will be killed.
#    RETRY - The time in seconds between checks for whether the target
#        task is still running.

# Validate number of command line arguments.
if (( $# != 4 )); then
   echo stop_loading: Wrong number of arguments.
   exit 1
fi

PID=$1
FILE=$2
TOTAL_INTERVAL=$3
TEST_INTERVAL=$4

# Create the stop file.
touch $FILE

# Loop waiting for the task to disappear (because it terminated cleanly)
declare -i I
I=0
while (( $I < $TOTAL_INTERVAL )); do
   # If the guy has gone away, we're done.
   if (( `ps -f -p $PID | wc -l` == 1 )); then
      exit
   fi
   # Sleep and then try again.
   sleep $4
   let I=$I+$TEST_INTERVAL
done

# If we exceed the total wait time, just kill the guy.
echo Aborting application.
kill -9 $PID
