#!/bin/sh

#  Usage: run [ -nice N ] [-mv | -cp ] [host_name] program_name [args]
#    runs a program in the background (on optionally given host)
#    move or copy program_name to program_name.host_name.process_id
#    keeps output in program_name.host_name.process_id.log
#
#  one way to kill the program: terminate program_name
#  one to check its status: chek program_name

test $# -gt 0 || exec sed -n 's/^#  //p' "$0"

OUT_NAME=~/Siegel_Numerics/Logs/;
#STACKSIZE=294912
#GROUP=3p3q

NICE="0"
MV="mv"

while :; do
  case "$1" in
    -nice) NICE="$2" ; shift ; shift ;;
    -cp)   MV=cp     ; shift ;;
    -mv)   MV=mv     ; shift ;;
    *)     break ;;
  esac
done

H=`hostname`


#FIND=`ypcat hosts | egrep "$1"`
#FIND=`hosts | egrep "$1"`

if [ -n "$FIND" ]; then
  HOST="$1"
  shift
else
  HOST="$H"
fi

test -x "$1" || exec echo "file $1 not executable"

addpath() {
  case "$1" in
    /*) echo -n "$1" ;;
    *)  echo -n "$PWD/$1" ;;
  esac
}

RUN="`addpath $0`"
PROG="`addpath $1`"
shift

test "$HOST" = "$H" || exec ssh -n "$HOST" "$RUN" -nice $NICE "-$MV" "$PROG" "$@"

cd "`dirname $PROG`"
PROG="`basename $PROG`"

for N in 1 2 3 4 5 6 7 8 9 0; do
  test -f "$OUT_NAME$PROG.$H.$N" || break
  echo "found $PROG.$H.$N"
done

test $N -eq 0 && exec echo "sorry, delete some of these files"

$MV "$PROG" "$OUT_NAME$PROG.$H.$N"
echo "Starting $PROG No $N on $H on `date`" | tee "$OUT_NAME$PROG.$H.$N.log"
"$OUT_NAME$PROG.$H.$N" "$@" >> "$OUT_NAME$PROG.$H.$N.log" 2>&1 &
echo "$H $!" >  "$OUT_NAME$PROG.$H.$N.pid"

renice $NICE -p $!
#chgrp "$GROUP" "$PROG.$H.$N"*
