#! /bin/sh

# usage: respawn [-append] [-stderr FILE] [-stdout FILE] [-sleep TIME]
#                [-pid FILE] [-tag STRING] [-exit CODE]

append=0
unset name
time=10
tag=$0
code=0

while [ $# -ne 0 ]
do
    arg=$1
    shift
    case $arg in
	-append)
	    append=1;;
	-stderr)
	    name=${1:?missing argument for -stderr}
	    shift
	    if [ $append -eq 1 ]; then
		exec 2>>$name
		append=0
	    else
		exec 2>$name
	    fi;;
        -stdout)
	    name=${1:?missing argument for -stdout}
	    shift
	    if [ $append -eq 1 ]; then
		exec >>$name
		append=0
	    else
		exec >$name
	    fi;;
	-sleep)
	    time=${1:?missing argument for -sleep}
	    shift;;
	-pid)
	    name=${1:?missing argument for -pid}
	    shift
	    if [ $append -eq 1 ]; then
		echo $$ >>$name
		append=0
	    else
		echo $$ >$name
	    fi;;
	-tag)
	    tag=${1:?missing argument for -tag}
	    shift;;
	-exit)
	    code=${1:?missing argument for -exit}
	    shift;;	    
	*)  echo >&2 "$tag: invalid argument: $arg"
	    exit 1
    esac
done

echo "$tag: start"
sleep $time
echo "$tag: stop"
exit $code
