#! /usr/bin/env bash
set -x

if [[ "$#" != 2 ]] ; then
    cat<<EOF 1>&2
$0: You have called hwrf_submit.sh incorrectly.  

    Syntax: hwrf_submit.sh INPUT_SCRIPT.shell OUTPUT_SCRIPT.sh

This script reads in an input .shell script, parses it with
\${USHhwrf}/hwrf_stream_parse.pl and then writes out the result in
OUTPUT_SCRIPT.sh.  Next, it submits OUTPUT_SCRIPT.sh to LoadLeveler
via llsubmit.

You MUST specify BOTH arguments: the INPUT_SCRIPT.shell and the
OUTPUT_SCRIPT.sh.  You provided $# arguments.  Aborting.
EOF

    exit 1
fi

function qsub_stdin {
    qsub < "$1"
}

ATCFID="${ATCFID:-$STID}"

# Try to figure out the year:
YEAR="${YEAR:-$YYYY}"
YEAR="${YEAR:-${YMDH:0:4}}"
YEAR="${YEAR:-${INPYMDH:0:4}}"

name=$( basename "$2" )

if [[ -z "$WHERE_AM_I" ]] ; then
    export WHERE_AM_I="$USHhwrf/hwrf_where_am_i.sh"
fi

if [[ ! -z "$ATCFID" && ! -z "$EXPT" && "$WHERE_AM_I" == jet ]] ; then
    eval $( $USHhwrf/hwrf_reservation.sh $ATCFID $EXPT $YEAR )
fi

if [[ ! -x "${USHhwrf}/hwrf_stream_parse.pl" ]] ; then
    echo "$0: File \"${USHhwrf}/hwrf_stream_parse.pl\" is not a file or is not executable.  Aborting." 1>&2
    exit 2
fi

${USHhwrf}/hwrf_stream_parse.pl $1 $2 
if [[ "$?" != 0 ]] ; then
    echo "$0: Program \"${USHhwrf}/hwrf_stream_parse.pl\" returned non-zero exit value $?.  Aborting." 1>&2
    exit 3
fi

if [[ "$WHERE_AM_I" == jet ]] ; then
    outfile=$( cat $2 | egrep '^#\$.*\.out' | perl -ne 's,.*?(\S+)\s*$,$1,g ; print' )
    errfile=$( cat $2 | egrep '^#\$.*\.err' | perl -ne 's,.*?(\S+)\s*$,$1,g ; print' )
    
    rm -f "$outfile" "$errfile"
    
    echo $2
    
    # qsub is not in the default path on cron servers on jet:
    export PATH=$PATH:/usr/local/esrl/bin/
    exe=qsub
elif [[ "$WHERE_AM_I" == zeus ]] ; then
    # Assume Zeus, and use qsub
    outfile=$( cat $2 | egrep '^#\$.*\.out' | perl -ne 's,.*?(\S+)\s*$,$1,g ; print' )
    errfile=$( cat $2 | egrep '^#\$.*\.err' | perl -ne 's,.*?(\S+)\s*$,$1,g ; print' )
    rm -f "$outfile" "$errfile"

    exe=qsub_stdin
else
    exe=llsubmit
fi

if [[ ! -z "$DATA" && -d "$DATA" ]] ; then
    if [[ ! -d "$DATA/job-ids/" ]] ; then
        "$USHhwrf/hwrf_mkdirp.sh" "$DATA/job-ids"
    fi
    jobfilebase="$DATA/job-ids/$name-$( date +%s )-$$"
    jobfile="$jobfilebase.jobid"

    echo "========================================================================" >> "$DATA"/submit.out 2>&1
    echo "== hwrf_submit $1 $2" >> "$DATA"/submit.out 2>&1
    $exe "$2" | tee "$jobfile" 2>&1 | tee -a "$DATA"/submit.out
    ret="$?"

else
    $exe "$2"
    ret="$?"
fi

if [[ "$ret" == 999 ]] ; then
    # Special value 999 means no job id was produced
    exit 5
fi

if [[ "$ret" != 0 ]] ; then
    echo "$0: $exe $2 returned a non-zero exit status $ret.  Aborting."  1>&2
    exit 4
fi

exit 0
