#! /bin/sh
#  dmtproc_enabled
#
#  Return the current node name.
dmtproc_enabled() {
    local procdir=`dmtproc_dir $*`
    [ x$procdir != x ] && [ ! -e $procdir/disable ]
}
#
#  dmtproc_mynode
#
#  Return the current node name.
dmtproc_mynode() {
    echo `uname -n | sed -e 's,\..*$,,g'`
}
#
#  dmtproc_node
#
#  Return the node name associated with the specified process.
dmtproc_node() {
    if [ $# -lt 2 ]; then
	dmtproc_mynode
    else
	echo $2
    fi
}
#
#  dmtproc_dir <proc-id> [<node-id>]
#
#  return the process directory. If the node is not specified 
#  the current node name is used. 
dmtproc_dir() {
    local proc=$1
    local node=`dmtproc_node $*`
    local procdir="$procroot/Process_List_$node/$proc"
    if [ ! -e $procdir/args ]; then
	echo "Process $proc not found on node $node" >&2
	procdir=""
    fi
    echo $procdir
}
#
#  dmtproc_pid <proc-id> [<node-id>]
#
#  return the process directory. If the node is not specified 
#  the current node name is used. 
dmtproc_pid() {
    local procdir=`dmtproc_dir $*`
    [ x$procdir != x ]  && \
    [ -h $procdir/pid ] && \
    echo `/bin/ls -l $procdir/pid | sed -e 's,^.* -> ,,g'`
}
#
#  dmtproc_restarts <proc-id> [<node-id>]
#
#  return the process directory. If the node is not specified 
#  the current node name is used. 
dmtproc_restarts() {
    local procdir=`dmtproc_dir $*`
    [ x$procdir != x ] && \
	[ -h $procdir/restarts ] && \
	echo `/bin/ls -l $procdir/restarts | sed -e 's,^.* -> ,,g'`
}
#
#   dmtproc_running
#
dmtproc_running() {
    local pid=`dmtproc_pid $*`
    [ $? -eq 0 ] && [ x$pid != xNA ]
}
#
#   dmtproc_status
#
dmtproc_status() {
    local procdir=`dmtproc_dir $*`
    if [ ! -d $procdir ]; then
        echo "unknown"
    elif [ dmtproc_running $* ]; then
	echo "running"
    elif [ -e $procdir/disable ]; then
	echo "disabled"
    else
	echo "stopped"
    fi
}
#
#  Stop the specified pid and wait
#
dmtproc_stop_pid() {
    local pid=$1
    kill -TERM $pid
    while kill -0 $pid 2> /dev/null; do 
	echo "waiting for pid $pid to terminate..." 
	sleep 2
    done
}
#
#  whowhatwhere
for defs in /etc/default/dmt-procmgt $HOME/.dmtprocmgtdefs ./.dmtprocmgtdefs; do
   [ -f $defs ] && . $defs
done
execuser=${PROCMGT_RUN_USER:-dmtexec}
exechome=`eval cd ~$execuser; pwd`
procroot=${PROCMGT_PROCESS_ROOT:-$exechome}
