#!/bin/sh

QueueName=long.q
UserName=`whoami`
EmailAddress=$UserName\@fmrib.ox.ac.uk
Arch=
EmailOpts=a
POSIXLY_CORRECT=1
export POSIXLY_CORRECT
usage  ()
{
if [ x$1 = xShowVersion ] ; then
  echo "V1.0beta qsub wrapper for Sun Grid Engine\n"
fi

  cat <<EOF
Usage: batch [-q <queuename>] [-N <jobname>] <command>

batch gzip *.img *.hdr
batch -q short.q gzip *.img *.hdr
batch -a darwin regscript rawdata outputdir ...

  -q <queuename>        Possible values for <queuename> are "verylong.q", "long.q" 
                        and "short.q". See below for details
                        Default is "long.q".
  -N <jobname>          The string <jobname> will be used for the output files
                        and the job name in qstat output.
  -j <jid>		Job hold. Run this job after <jid> has completed.
  -h			Display this help text.
  -a <arch-name>        Architecture [darwin only at present]
  -p <job-priority>     Lower priority [0:-1024] default = 0                 
  -M <email-address>    Who to email. default = `whoami`@fmrib.ox.ac.uk 
  -v                    Verbose mode.

Queues:

There are three batch queues configured on the cluster, each with defined CPU
time limits.

short.q:    This queue is for jobs which last less then 2h. There are two slots 
            per node.
long.q:     This queue is for jobs which last less than 24h. There are two slots
            per node.
verylong.q: This queue is for jobs which will take longer than 24h CPU time.
            There is one slot per node, and jobs on this queue have a nice value
            of 5. If jobs enter the short.q queue then items running on this
            queue are suspended and resumed on completion of the short.q task.

EOF
}

nargs=$#
if [ $nargs -eq 0 ] ; then
  echo "What? No arguments!"
fi

set -- `getopt q:N:a:p:M:j:hv $*`
result=$?
if [ $result != 0 ] ; then
  echo "What? Your arguments make no sense!"
fi

if [ $nargs -eq 0 ] || [ $result != 0 ] ; then
  usage
  exit 1
fi
while [ $1 != -- ] ; do
  case $1 in
    -q)
      QueueName=$2
      shift;;
    -N)
      JobName=$2
      shift;;
    -a)
      Arch="-l arch=$2"
      shift;;
    -j)
      JobHold="-hold_jid $2"
      shift;;
    -p)
      Priority="-p $2"
      shift;;
    -M)
      echo Mailing $2
      EmailAddress=$2
      shift;;
    -v)
      Verbose=1
      ;;
    -h)
      usage ShowVersion
      exit 1
  esac
  shift  # next flag
done

shift
JobName=`basename $1`
JobSpec=$@

BaseCommand="qsub -V -cwd -shell n -b y -r y -m $EmailOpts -M $EmailAddress"
Command="$BaseCommand -q $QueueName -N $JobName $Arch $JobHold $Priority $JobSpec"

if [ "${Verbose}" != "" ] ; then
  echo Running command: $Command
else
  exec $Command
fi
