#!/bin/bash

commandtorun=""
nodes=1
ntasks=1
mem=2G
maxtime="6-23:00"
outfile=""
partition=""
cpuspertask=1

function usage
{
cat << EOF

Submit commands to SLURM

Usage: slurmit [options] "command to execute"

Submission script for SLURM

OPTIONS:
        -h      Show this message
        -c      Number of processors per task (--cpus-per-task parameter) (dedault 1)
        -m      memory required per node (--mem parameter) (defualt "2G")
        -n      maximum number of tasks (--ntasks parameter) (default 1)
        -o      Output file (stdout and stderr) (default undefined)
        -p      Parition (e.g. "tgac-medium") (default undefined)
        -t      Time limit (--time parameter) (default "6-23:00")
        -N      minimum number of nodes (--nodes parameter) (default 1)

Example: slurmit -o logfile.txt "ls -l"

Don't forget to backslash dollar variables, as appropriate.

EOF
}


while getopts c:hm:n:o:p:t:N: OPTION
do
    case $OPTION in
                c) cpuspertask=$OPTARG;;
                h) usage ; exit 1 ;;
                m) mem=$OPTARG;;
                n) ntasks=$OPTARG;;
                o) outfile=" -o $OPTARG";;
                p) partition=" -p $OPTARG";;
                t) maxtime=$OPTARG;;
                N) nodes=$OPTARG;;
    esac
done
shift $((OPTIND-1))

commandtorun=$@

if [ "$commandtorun" == "" ] ; then
    echo "You must specify a command to run"
    exit
fi

sbatch --nodes ${nodes} --cpus-per-task=${cpuspertask} --ntasks ${ntasks} --time ${maxtime} --mem ${mem}${outfile}${partition} --wrap="echo \"SLURM job output\" ; echo "" ; echo \"Command: ${commandtorun}\" ; echo \"Job ID: \${SLURM_JOB_ID}\" ; echo -n \"Start time: \" ; date ; printf \"%0.s-\" {1..70} ; printf \"\n\n\" ; ${commandtorun} ; printf \"\n\" ; printf \"%0.s-\" {1..70} ; printf \"\n\n\" ; sstat -j \${SLURM_JOB_ID}.batch ; printf \"\n\" ; echo \"SLURM ended\"; echo -n \"End time: \" ; date"
