#! /bin/sh
syntax() {
    echo "Command syntax:"
    echo "   dmt-mon_restart [--args \"<cmd>\"] [--restart <n>] <process>" \
	 "[<node>]"
}

prefix=/usr
exec_prefix=${prefix}
[ -f ${exec_prefix}/bin/dmt-scriplets ] || exit 1
. ${exec_prefix}/bin/dmt-scriplets 

rescnt=10
args=""
while [ `echo $1 | grep -c ^--` != 0 ]; do
    case $1 in
    --restart) 
        rescnt=$2
	shift 2
	;;
    --args)
	args="$2"
	shift 2
	;;
    --help)
	echo "The dmt restart command allows the user to restart a dmt process"
	echo "managed by procmgt. The command line arguments given to the "
	echo "process may optionally be replaced by a new commad line string."
	echo "The number of restarts defaults to 10 be may be specified with"
	echo "the --restart option"
	echo "The command has the following syntax: "
	echo "  dmt restart [--help] [--args \"<new-arguments>\"] "
	echo "              [--restart <count>] <process> [<node>]"
	echo " "
	;;
    *)
	echo "error: unrecognized keyword: $1"
	exit 1
	;;
    esac
done


node=`dmtproc_node $*`
procdir=`dmtproc_dir $*`
if [ x$procdir = x ]; then
    echo "Process $1 not running on node $node"
    syntax
    exit 1
fi

# ---> test for disabled restarts
if [ -f $procdir/disable ]; then
    echo "Process $proc restarts are disabled. Use:"
    echo " 'dmt-mon_enable $*'"
    echo "to enable the process."
    exit 1
fi

# --->  Execute this request on a different node if necessary
mynode=`dmtproc_mynode`
if [ "x$node" != "x$mynode" -o "x$USER" != "x$execuser" ]; then
    echo "Restarting process $1 on node $node"
    xtra=""
    if [ "$rescnt" != "10" ]; then
	xtra="--restart $rescnt"
    fi
    if [ -n "$args" ]; then
	xtra="$xtra --args '$args'"
    fi
    ssh ${execuser}@$node dmt-mon_restart $xtra $*
    exit $?
fi

# --->  Check for new arguments
if [ -n "$args" ]; then
    if dmtproc_running $*; then
	pid=`dmtproc_pid $*`
	touch $procdir/disable
        dmtproc_stop_pid $pid
	sleep 2
        [ `dmtproc_restarts $*` != 0 ] || ln -sf $rescnt $procdir/restarts
	echo "$args" > $procdir/args
	rm $procdir/disable
        pkill -HUP procmgt
    else
        [ `dmtproc_restarts $*` != 0 ] || ln -sf $rescnt $procdir/restarts
	echo "$args" > $procdir/args
        pkill -HUP procmgt
    fi

# --->  Check for running process.
elif dmtproc_running $* ; then
    pid=`dmtproc_pid $*`
    echo "Process: $proc is currently running as process $pid."
    echo "It will be killed and restarted automatically!"
    [ `dmtproc_restarts $*` != 0 ] || ln -sf $rescnt $procdir/restarts
    /usr/bin/kill $pid

# ---> restart the process.
else
    [ `dmtproc_restarts $*` != 0 ] || ln -sf $rescnt $procdir/restarts
    pkill -HUP procmgt
fi
