#!/bin/sh
#
# count --
#	Simple program to demonstrate restartable job management with pmake.
#
#	$Id: count,v 1.1 1993/02/11 23:56:22 stolcke Exp $
# 	
# Usage: count [-notrap] [-noevict] savefile [maxcount]
#
# will count from 1 to maxcount, saving state in savefile so it can restart
# when interrupted.  It will generate its own interrupts once in a while to
# test the mechanism.  Normally, the interrupt is trapped to a handler
# that will save the current state and exit in an orderly manner (with code 1).
# This can be used with the .RESTART attribute in pmake.
# The -notrap option skips the interrupt and lets the signal kill the process
# directly. This will look like an eviction to pmake and test the automatic
# restart facility in the remote module.
# The -noevict will suppress the internal interrupt generation.
#
# Note that SIGUSR2 is the signal used to notify the process of impending
# eviction, while SIGXCPU (or SIGTERM on SYSV systems) is used to force the
# eviction itself.  To be a nice boy we should exit on SIGUSR2.
#
count=1
sleep=2
evict=31	# SIGUSR2
suicide=10

if [ $1 = -notrap ]; then
	notrap=yes
	evict=24	# SIGXCPU
	shift
fi
if [ $1 = -noevict ]; then
	noevict=yes
	shift
fi

savefile=${1-count.save}
maxcount=${2-30}

#
# savefile present means we should restart where our predecessor left off
#
if [ -f $savefile ]; then
	read count < $savefile
fi

#
# set up signal handler to catch eviction signal and write savefile
#
if [ ! "$notrap" ]; then
	trap	'echo "`date` saving count in $savefile" >&2; \
		 echo $count > $savefile; \
		 exit 1' $evict
fi

while [ $count -le $maxcount ]; do
	echo $count
	sleep $sleep
	count=`expr $count + 1`
	#
	# if we are not trapping the eviction signal ourselves the savefile
	# has to be kept up to date
	#
	if [ $notrap ]; then
		echo $count > $savefile
	fi
	#
	# every so often, simulate an eviction 
	#
	if [ ! "$noevict" ]; then
		suicide=`expr $suicide - 1`
		if [ $suicide -eq 0 ]; then
			kill -$evict $$
		fi
	fi
done

#
# remove savefile and tell pmake we're done
#
echo "count done"
rm -f $savefile
exit 0
