#!/bin/bash

. `dirname $0`/blah_load_config.sh

usage_string="Usage: $0 -c <command> [-i <stdin>] [-o <stdout>] [-e <stderr>] [-x <x509userproxy>] [-v <environment>] [-s <yes | no>] [-- command_arguments]"

###############################################################
# Parse parameters
###############################################################

while getopts "i:o:e:c:s:v:V:dw:q:n:rp:l:x:j:T:I:O:R:C:" arg 
do
    case "$arg" in
    i) stdin="$OPTARG" ;;
    o) stdout="$OPTARG" ;;
    e) stderr="$OPTARG" ;;
    v) envir="$OPTARG";;
    V) environment="$OPTARG";;
    c) the_command="$OPTARG" ;;
    s) stgcmd="$OPTARG" ;;
    d) debug="yes" ;;
    w) workdir="$OPTARG";;
    q) queue="$OPTARG";;
    n) mpinodes="$OPTARG";;
    r) proxyrenew="yes" ;;
    p) prnpoll="$OPTARG" ;;
    l) prnlifetime="$OPTARG" ;;
    x) proxy_string="$OPTARG" ;;
    j) creamjobid="$OPTARG" ;;
    T) temp_dir="$OPTARG" ;;
    I) inputflstring="$OPTARG" ;;
    O) outputflstring="$OPTARG" ;;
    R) outputflstringremap="$OPTARG" ;;
    C) req_file="$OPTARG";;
    -) break ;;
    ?) echo $usage_string
       exit 1 ;;
    esac
done

# Command is mandatory
if [ "x$the_command" == "x" -o "$workdir" == "" ]
then
    echo $usage_string
    exit 1
fi

shift `expr $OPTIND - 1`
arguments=$*


# Setup stdin/out/err
if [ ! -z "$stdin" ] ; then
    if [ "${stdin:0:1}" != "/" ] ; then stdin=${workdir}/${stdin} ; fi
    arguments="$arguments <$stdin"
fi
if [ ! -z "$stdout" ] ; then
    if [ "${stdout:0:1}" != "/" ] ; then stdout=${workdir}/${stdout} ; fi
    arguments="$arguments >$stdout"
fi
if [ ! -z "$stderr" ] ; then
    if [ "${stderr:0:1}" != "/" ] ; then stderr=${workdir}/${stderr} ; fi
    if [ "$stderr" == "$stdout" ]; then
        arguments="$arguments 2>&1"
    else
        arguments="$arguments 2>$stderr"
    fi
fi

# Write the NQS script
# TODO Does the submit script need to live beyond the life of this
#   script? If so, how do we name the submit script so that it won't
#   collide with submit scripts of other jobs, yet still be able to
#   recreate the name in the status/cancel scripts that we can remove
#   the script?
nqs_script=$workdir/.nqs_submit.$$
nqs_submit_output=$workdir/.nqs_submit_output.$$
cat >$nqs_script <<EOF
#
# NQS submit script generated by `basename $0`
# on `/bin/date`
#
# NQS directives:
# @\$-s /bin/bash
EOF

if [ "$queue" != "" ] ; then
    echo "# @\$-q $queue" >>$nqs_script
fi

if [ "$mpinodes" != "" ] ; then
    echo "# @\$-lP $mpinodes" >>$nqs_script
fi

# Set the required environment variables (escape values with double quotes)
if [ "x$environment" != "x" ] ; then
    echo "" >> $nqs_script
    echo "# Setting the environment:" >> $nqs_script
    eval "env_array=($environment)"
    for  env_var in "${env_array[@]}"; do
         echo export \"$env_var\" >> $nqs_script
    done
else
    if [ "x$envir" != "x" ] ; then
        echo "" >> $nqs_script
        echo "# Setting the environment:" >> $nqs_script
        echo "`echo ';'$envir | sed -e 's/;[^=]*;/;/g' -e 's/;[^=]*$//g' | sed -e 's/;\([^=]*\)=\([^;]*\)/;export \1=\"\2\"/g' | awk 'BEGIN { RS = ";" } ; { print $0 }'`" >> $nqs_script
    fi
fi

if [ "$proxy_string" != "" ] ; then
    echo "export X509_USER_PROXY=$proxy_string" >> $nqs_script
fi

# Cd to the job's directory
echo "cd $workdir" >> $nqs_script

# Now run the job
echo "# Command to execute:" >> $nqs_script
echo "$the_command $arguments" >> $nqs_script
echo "user_retcode=\$?" >> $nqs_script

echo "exit \$user_retcode" >> $nqs_script

###############################################################
# Submit the script
###############################################################
cd $workdir

${nqs_binpath}qsub $nqs_script >$nqs_submit_output
retcode=$?
if [ "$retcode" != "0" ] ; then
    rm -f $nqs_script $nqs_submit_output
    echo Error # for the sake of waiting fgets in blahpd
    exit 1
fi

grep -E -q 'Request [0-9]+[.][^ ]+ submitted to queue: [^ ]+' $nqs_submit_output
retcode=$?
if [ "$retcode" != "0" ] ; then
    rm -f $nqs_script $nqs_submit_output
    echo Error # for the sake of waiting fgets in blahpd
    exit 1
fi

jobID=`awk '{ print $2 }' <$nqs_submit_output`

rm -f $nqs_submit_output
rm -f $nqs_script

# Compose the blahp jobID ("nqs/" + nqs jobid)
echo "BLAHP_JOBID_PREFIXnqs/$jobID"

exit $retcode
