#!/bin/bash
#DMACHINE run command.
#    dmboot -- start up dmachinemon using dsh
#    Copyright (C) 2001 Junichi Uekawa
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# created 20 Dec 2001 Junichi Uekawa
#depends: tempfile (debianutils)

DSHOPT=
RUNGDB=

if test -f ~/.dmrc; then
    . ~/.dmrc
fi


if [ -z "$DMACHINELIST" ]; then
    DMACHINELIST=~/.dmachinelist
fi


if [ -z "$CLIENTPORT" ]; then
    CLIENTPORT=3007
fi

if [ -z "$NODEPORT" ]; then
    NODEPORT=3008
fi

while [ -n "$1" ]; do
    case "$1" in
	-np|--np)
	    shift;
	    TF=$(tempfile)
	    head -"$1" ${DMACHINELIST} > "$TF"
	    DMACHINELIST="$TF";
	    shift;
	    ;;
	-rc|--rc)
	    shift;
	    . "$1"
	    shift;
	    ;;
	-d|--debug)
	    doit=echo 
	    shift;
	    ;;
	-g|--gdb)
	    RUNGDB=yes
	    DSHOPT="$DSHOPT -i "
	    shift;
	    ;;
	-f|--file)
	    shift
	    DMACHINELIST="$1"
	    shift
	    ;;
	-n)
	    shift;
	    DSHOPT="-n $1"
	    shift;
	    ;;
	--)
	    # this will end the list of options for dmrun
	    shift;
	    break;
	    ;;
	-*)
	    echo "Unknown option \"$1\"" >&2
	    exit 1;
	    ;;
	*)
	    # A non-option statement is given, possibly the progname.
	    break;
	    ;;
    esac
done


if [ ! -f "${DMACHINELIST}" ]; then
    echo "Error: ${DMACHINELIST} does not exist!!" >&2 
fi


PROGNAME="$1"
shift 

if [ "$RUNGDB" = "yes" ]; then
    ($doit dsh ${DSHOPT} -f "$DMACHINELIST" -c -M -- gdb $PROGNAME )
else
    ($doit dsh ${DSHOPT} -f "$DMACHINELIST" -c -M -- $PROGNAME -c $CLIENTPORT -n $NODEPORT -p $(hostname) "$@" < /dev/null )&
fi

wait
