#!/bin/sh

if [ -x "/usr/bin/basename" ]
then
  BASENAME_CMD="/usr/bin/basename"
else
  BASENAME_CMD="/bin/basename"
fi
CAT_CMD="/bin/cat"
CHMOD_CMD="/bin/chmod"
CHOWN_CMD="/bin/chown"
if [ -x "/usr/bin/dirname" ]
then
  DIRNAME_CMD="/usr/bin/dirname"
else
  DIRNAME_CMD="/bin/dirname"
fi
ECHO_CMD="/bin/echo"
LS_CMD="/bin/ls"
MKDIR_CMD="/bin/mkdir"
PWD_CMD="/bin/pwd"
SSH_CMD="/usr/bin/ssh -o BatchMode=yes -o CheckHostIP=no"
SCP_CMD="/usr/bin/scp -o BatchMode=yes -o CheckHostIP=no"
STAT_SIZE="/usr/bin/stat --format=%s"
TAR_CMD="/bin/tar"
TOUCH_CMD="/bin/touch"
RM_CMD="/bin/rm"
MV_CMD="/bin/mv"

sperror()
{
    if [ "$1" != "" ]
    then
        status="$1"
    else
        status=0
    fi

    if [ "$status" != "0" ]
    then
        $ECHO_CMD "spartand: $2" >>error
        if [ "$3" != "" ]
        then
            $ECHO_CMD "    $3" >>error
        fi
        if [ $status -ne -1 ]
        then
            $ECHO_CMD "        failed with status=$status" >>error
        fi
        if [ "$JOBNAME" != "@@" ]
        then
            $SPAR_SUBMIT/sp_inuse --remove --silent "$JOBNAME"
        fi
        if [ "$BUILDER_PID" != "" ]
        then
            $SPAR_SUBMIT/sp_postjob "$JOBNAME" $$ -error "$2"
        fi
        exit 1
    fi
}

spderror()
{
    if [ "$1" != "" ]
    then
        status="$1"
    else
        status="0"
    fi

    if [ "$status" != "0" ]
    then
        if [ "$JOBNAME" != "@@" ]
        then
            $SPAR_SUBMIT/sp_inuse --remove --silent "$JOBNAME"
        fi
        if [ "$status" -eq 1 ]
        then
            errmsg="Document path not specified"
        elif [ "$status" -eq 2 ]
        then
            errmsg="Analysis failed, please check output for details"
        elif [ "$status" -eq 3 ]
        then
            errmsg="User terminated analysis"
        elif [ "$status" -eq 4 ]
        then
            errmsg="Analysis signalled"
        else
            errmsg="Unknown error occurred"
        fi
 
        if [ "$BUILDER_PID" != "" ]
        then
            $SPAR_SUBMIT/sp_postjob "$JOBNAME" $$ -error "$errmsg"
        fi
        exit 2
    fi
}

SLOG=""

SLOG=""
L_USER=""
L_HOST=`hostname -s`

inhost="no"
inuser="no"
inremote="no"
JOBNAME="@@"
R_HOST="@@"
R_USER="@@"
R_JOBNAME="@@"
R_JOBBASENAME="@@"
R_JOBEXTENSION=""

for i in "$@"
do
    if [ $inhost = "yes" ]
    then
        R_HOST="$i"
        inhost="no"
    elif [ $inuser = "yes" ]
    then
        R_USER="$i"
        inuser="no"
    elif [ $inremote = "yes" ]
    then
        R_JOBNAME="$i"
        inremote="no"
    else
        case $i in
        --host)
            inhost="yes"
            ;;
        --user)
            inuser="yes"
            ;;
        --remote-name)
            inremote="yes"
            ;;
        *)
            JOBNAME="$i"
            ;;
        esac
    fi
done

if [ -n "$HOME" ]
then
    if [ ! -d $HOME/.spartanrc ]
    then
        ${MKDIR_CMD} $HOME/.spartanrc
    fi

    if [ ! -f $HOME/.spartanrc/submit_spartan ]
    then
        ${TOUCH_CMD} $HOME/.spartanrc/submit_spartan
    fi
fi

JOBFORMAT="SpartanDirectory"
if [ -f "$JOBNAME" ]
then
    JOBFORMAT="SpartanDocument"
    JOBBASENAME=`$BASENAME_CMD "$JOBNAME" .spartan`
    JOBDIRNAME=`$DIRNAME_CMD "$JOBNAME"`
    if [ "$JOBDIRNAME/$JOBBASENAME.spartan" != "$JOBNAME" ]
    then
        sperror -1 \
        "Error, $JOBNAME is not a Spartan document"
    fi
elif [ ! -e _spartan ] && [ ! -e _spartandir ]
then
    if [ -n "$JOBNAME" ] && [ -d "$JOBNAME" ]
    then
        cd "$JOBNAME"
        sperror $? \
        "Error, unable to change directory to $JOBNAME"

        if [ ! -e _spartan ] && [ ! -e _spartandir ]
        then
            sperror -1 \
            "Error, directory $JOBNAME is not a Spartan molecule directory"
        fi
    else
        sperror -1 \
        "Error, current directory is not a Spartan molecule directory"
    fi
fi

if [ "$JOBFORMAT" == "SpartanDirectory" ]
then
    if [ "$R_JOBNAME" != "@@" ]
    then
        R_JOBBASENAME=`$BASENAME_CMD "$R_JOBNAME" .spartan`
        if [ "$R_JOBBASENAME.spartan" == "$R_JOBNAME" ]
        then
            R_JOBEXTENSION=".spartan"
        fi
        R_JOBNAME="$R_JOBNAME.tgz"
    fi
elif [ "$JOBFORMAT" == "SpartanDocument" ]
then
    if [ "$R_JOBNAME" != "@@" ]
    then
        R_JOBBASENAME=`$BASENAME_CMD "$R_JOBNAME" .spartan`
        if [ "$R_JOBBASENAME.spartan" == "$R_JOBNAME" ]
        then
            R_JOBEXTENSION=".spartan"
        fi
    fi
fi

if [ -e error ]
then
   ${RM_CMD} error
fi

if [ "$USER" == "" ]
then
    if [ "$LOGNAME" == "" ]
    then
        if [ "$USERNAME" != "" ]
        then
            L_USER="$USERNAME"
        fi
    else
        L_USER="$LOGNAME"
    fi
else
    L_USER="$USER"
fi

if [ "$L_USER" = "" ]
then
    sperror -1 "Can't determine user's name"
else
    SLOG="/tmp/spartan_${L_USER}.log"
fi

if [ -e "$SLOG" ]
then
    if [ ! -w "$SLOG" ]
    then
        sperror -1 "User can't write to $SLOG"
    fi
else
    ${TOUCH_CMD} "$SLOG"
        sperror $? \
        "User can't create $SLOG" \
        "$TOUCH_CMD $SLOG"

    ${CHMOD_CMD} 644 "$SLOG"
        sperror $? \
        "User can't change access permissions on $SLOG" \
        "$CHMOD_CMD 644 $SLOG"

    ${CHOWN_CMD} "$L_USER" "$SLOG"
        sperror $? \
        "User can't change ownership of $SLOG" \
        "$CHOWN_CMD $L_USER $SLOG"
fi

R_QUEUE_PATH=""
if [ $R_HOST != "@@" -a "$R_JOBNAME" != "@@" ]
then
    SSH_USER=""
    SCP_USER=""
    if [ $R_USER != "@@" ]
    then
        SSH_USER="-l $R_USER"
        SCP_USER="$R_USER@"
    fi

    R_QUEUE_PATH=`${SSH_CMD} $R_HOST $SSH_USER ${CAT_CMD} /var/spartan/remote_job_path`
    sperror $? \
        "Can't obtain remote queue path" \
        "$SSH_CMD $R_HOST $SSH_USER ${CAT_CMD} /var/spartan/remote_job_path"

    if [ "$JOBFORMAT" == "SpartanDirectory" ]
    then
        ${TAR_CMD} -czf "$R_JOBNAME" *
        sperror $? \
            "Can't create tar archive"  \
            "${TAR_CMD} -czf "$R_JOBNAME" *"

        ${SCP_CMD} "$R_JOBNAME" $SCP_USER$R_HOST:"'$R_QUEUE_PATH/$R_JOBNAME'"
        sperror $? \
            "Can't copy job to remote" \
            "${SCP_CMD} $R_JOBNAME $SCP_USER$R_HOST:$R_QUEUE_PATH/$R_JOBNAME"

        L_SIZE=`$STAT_SIZE "$R_JOBNAME"`
        sperror $? \
            "Can't determine size of local job file" \
            "$STAT_SIZE $R_JOBNAME"

        R_SIZE=`${SSH_CMD} $R_HOST $SSH_USER $STAT_SIZE "'$R_QUEUE_PATH/$R_JOBNAME'"`
        sperror $? \
            "Can't determine size of remote job file" \
            "$SSH_CMD $R_HOST $SSH_USER $STAT_SIZE $R_QUEUE_PATH/$R_JOBNAME"

        if [ $L_SIZE -ne $R_SIZE ]
        then
            sperror -1 \
            "Size of local job file doesn't match size of remote job file"
        fi

        L_PWD=`$PWD_CWD`
        $ECHO_CMD $L_PWD >"$R_JOBNAME.working"

        ${SCP_CMD} "$R_JOBNAME.working"  $SCP_USER$R_HOST:"'$R_QUEUE_PATH/$R_JOBNAME.working'"
        sperror $? \
            "Unable to copy working file to remote" \
            "${SCP_CMD} $R_JOBNAME.working  $SCP_USER$R_HOST:$R_QUEUE_PATH/$R_JOBNAME.working"

    else
        ${SCP_CMD} "$JOBNAME" $SCP_USER$R_HOST:"'$R_QUEUE_PATH/$R_JOBNAME'"
        sperror $? \
            "Can't copy job to remote" \
            "${SCP_CMD} $JOBNAME $SCP_USER$R_HOST:$R_QUEUE_PATH/$R_JOBNAME"

        L_SIZE=`$STAT_SIZE "$JOBNAME"`
        sperror $? \
            "Can't determine size of local job file" \
            "$STAT_SIZE $JOBNAME"

        R_SIZE=`${SSH_CMD} $R_HOST $SSH_USER $STAT_SIZE "'$R_QUEUE_PATH/$R_JOBNAME'"`
        sperror $? \
            "Can't determine size of remote job file" \
            "$SSH_CMD $R_HOST $SSH_USER $STAT_SIZE $R_QUEUE_PATH/$R_JOBNAME"

        if [ "$L_SIZE" -ne "$R_SIZE" ]
        then
            sperror -1 \
            "Size of local job file doesn't match size of remote job file"
        fi

        ${SSH_CMD} $R_HOST $SSH_USER "$ECHO_CMD $JOBNAME >'$R_QUEUE_PATH/$R_JOBNAME.working'" 
        sperror $? \
            "Unable to create working file on remote" \
            "${SSH_CMD} $R_HOST $SSH_USER $ECHO_CMD $JOBNAME >$R_QUEUE_PATH/$R_JOBNAME.working"
    fi

else
    cd ..
fi

if [ "$BUILDER_PID" != "" ]
then
    $SPAR_SUBMIT/sp_postjob "$JOBNAME" $$ -pending
    status=$?
    if [ "$status" != "0" ]
    then
        $ECHO_CMD SPARTAND: sp_postjob "$JOBNAME" $$ -pending >>${SLOG}
        $ECHO_CMD SPARTAND: failed $status                    >>${SLOG}
    fi
fi

if [ "$BUILDER_PID" != "" ]
then
    $SPAR_SUBMIT/sp_postjob "$JOBNAME" $$ -running
    status=$?
    if [ "$status" != "0" ]
    then
        $ECHO_CMD SPARTAND: sp_postjob "$JOBNAME" $$ -running >> ${SLOG}
        $ECHO_CMD SPARTAND: failed $status                    >> ${SLOG}
    fi
fi

if [ "$R_HOST" != "@@" -a "$R_JOBNAME" != "@@" ]
then
    ${SSH_CMD} $R_HOST $SSH_USER /var/spartan/spartan_ssh "'$R_QUEUE_PATH/$R_JOBNAME'"
    sperror $? \
        "Remote submit failed" \
        "${SSH_CMD} $R_HOST $SSH_USER /var/spartan/spartan_ssh $R_QUEUE_PATH/$R_JOBNAME"

    working=1
    timestep=1
    totaltime=0
    until test $working -eq 0
    do
        ${SSH_CMD} $R_HOST $SSH_USER test -e "'$R_QUEUE_PATH/$R_JOBNAME.completed'"
        working=$?
        if [ $working -ne 0 ]
        then
            sleep $timestep
            totaltime=`expr $totaltime + $timestep`
            if [ $totaltime -le 20 ]
            then
                timestep=1
            elif [ $totaltime -le 40 ]
            then
                timestep=2
            elif [ $totaltime -le 100 ]
            then
                timestep=5
            elif [ $totaltime -le 300 ]
            then
                timestep=15
            elif [ $totaltime -le 600 ]
            then
                timestep=30
            else
                timestep=60
            fi
        fi
    done

    ${SSH_CMD} $R_HOST $SSH_USER $RM_CMD -f  "'$R_QUEUE_PATH/$R_JOBNAME.completed'"
    sperror $? \
        "Error occurred while removing $R_QUEUE_PATH/$R_JOBNAME.completed" \
        "${SSH_CMD} $R_HOST $SSH_USER $RM_CMD -f  $R_QUEUE_PATH/$R_JOBNAME.completed"

    if [ "$JOBFORMAT" == "SpartanDirectory" ]
    then
        $SCP_CMD $SCP_USER$R_HOST:"'$R_QUEUE_PATH/$R_JOBNAME'" "$R_JOBNAME"
        sperror $? \
            "Error occurred while copying job from remote to local" \
            " $SCP_CMD $SCP_USER$R_HOST:$R_QUEUE_PATH/$R_JOBNAME $R_JOBNAME"
    else
        $SCP_CMD $SCP_USER$R_HOST:"'$R_QUEUE_PATH/$R_JOBNAME'" "$JOBDIRNAME/$R_JOBNAME"
        sperror $? \
            "Error occurred while copying job from remote to local" \
            " $SCP_CMD $SCP_USER$R_HOST:$R_QUEUE_PATH/$R_JOBNAME $R_JOBNAME"

        $MV_CMD -f "$JOBDIRNAME/$R_JOBNAME" "$JOBNAME"
        sperror $? \
            "Error occurred while renaming job from remote to local" \
            " $RENAME_CMD $R_JOBNAME $JOBNAME"
    fi

    ${SSH_CMD} $R_HOST $SSH_USER $RM_CMD -f "'$R_QUEUE_PATH/$R_JOBNAME'"
    sperror $? \
        "Error occurred while deleting remote job archive" \
        "${SSH_CMD} $R_HOST $SSH_USER $RM_CMD -f  $R_QUEUE_PATH/$R_JOBNAME"

    if [ "$JOBFORMAT" == "SpartanDirectory" ]
    then
        ${TAR_CMD} -xzf "$R_JOBNAME"
        sperror $? \
            "Error unpacking job archive" \
            "${TAR_CMD} -xzf $R_JOBNAME"

        ${RM_CMD} "$R_JOBNAME"
        sperror $? \
            "Error deleting job archive" \
            "${RM_CMD} $R_JOBNAME"

        ${RM_CMD} "$R_JOBNAME.working"
        sperror $? \
            "Error deleting working file" \
            "${RM_CMD} $R_JOBNAME.working"
    fi

    if [ "$JOBFORMAT" == "SpartanDirectory" ]
    then
        #R_LIST_RESULTS=`${SSH_CMD} $R_HOST $SSH_USER $LS_CMD "'$R_QUEUE_PATH/$R_JOBBASENAME'"'.*'"$R_JOBEXTENSION.tgz" `
        ${SSH_CMD} $R_HOST $SSH_USER $LS_CMD "'$R_QUEUE_PATH/$R_JOBBASENAME'"'.*'"$R_JOBEXTENSION.tgz" > listresults
        if [ $? -eq 0 ]
        then
            L_PWD=`$PWD_CMD`
            cd ..
            #for i in ${R_LIST_RESULTS}
            #do
            #    ${SCP_CMD} $SCP_USER$R_HOST:$i .
            #    ${SSH_CMD} $R_HOST $SSH_USER $RM_CMD $i
            #    ${TAR_CMD} -xzf `$BASENAME_CMD $i`
            #    ${RM_CMD} `$BASENAME_CMD $i`
            #done
            while read LR_LINE
            do
                ${SCP_CMD} $SCP_USER$R_HOST:"'$LR_LINE'" .
                ${SSH_CMD} $R_HOST $SSH_USER $RM_CMD "'$LR_LINE'"
                LR_BASENAME=`$BASENAME_CMD "$LR_LINE"`
                ${TAR_CMD} -xzf "$LR_BASENAME"
                ${RM_CMD} "$LR_BASENAME"
            done <"$L_PWD/listresults"
            cd "$L_PWD"
            ${RM_CMD} listresults         
        fi

        if [ -e _inuse ]
        then
            ${RM_CMD} _inuse
            sperror $? \
                "Error deleting job inuse flag" \
                "${RM_CMD} _inuse"
        fi

        /bin/ls */_inuse 2>/dev/null >/dev/null
        if [ $? -eq 0 ]
        then
            $RM_CMD */_inuse
            sperror $? \
                "Error deleting job list inuse flags" \
                "${RM_CMD} */_inuse"
        fi
    else
        ${SSH_CMD} $R_HOST $SSH_USER $LS_CMD -1 "'$R_QUEUE_PATH/$R_JOBBASENAME'"'.*'"$R_JOBEXTENSION" > "$JOBDIRNAME/$R_JOBNAME".listresults

        while read LR_LINE
        do
            ${SCP_CMD} $SCP_USER$R_HOST:"'$LR_LINE'" "$JOBDIRNAME"
            ${SSH_CMD} $R_HOST $SSH_USER $RM_CMD "'$LR_LINE'"
        done <"$JOBDIRNAME/$R_JOBNAME".listresults
            
        ${RM_CMD} "$JOBDIRNAME/$R_JOBNAME".listresults
    fi

else
    # Run sp_spd in foreground so completed message is posted after
    # job completes.
    if [ "$SPAR_QUEUE_TYPE" = "INTERNAL" ]
    then
        ${SPAR_SUBMIT}/sp_spd --foreground --internal-default-queue -v 1 "$JOBNAME" >>${SLOG}
        spderror $? \
            "${SPAR_SUBMIT}/sp_spd --foreground --internal-default-queue -v 1 $JOBNAME >>${SLOG}"
    elif [ "$SPAR_QUEUE_TYPE" = "EXTERNAL" ]
    then
        if [ -z "$SPAR_QUEUE_NAME" ]
        then
            ${SPAR_SUBMIT}/sp_spd --foreground --external-default-queue -v 1 "$JOBNAME" >>${SLOG}
            spderror $? \
                "${SPAR_SUBMIT}/sp_spd --foreground --external-default-queue -v 1 $JOBNAME >>${SLOG}"
        else
            ${SPAR_SUBMIT}/sp_spd --foreground --external-queue $SPAR_QUEUE_NAME -v 1 "$JOBNAME" >>${SLOG}
            spderror $? \
                "${SPAR_SUBMIT}/sp_spd --foreground --external-queue $SPAR_QUEUE_NAME -v 1 $JOBNAME >>${SLOG}"
        fi
    else
        ${SPAR_SUBMIT}/sp_spd --foreground -v 1 "$JOBNAME" >>${SLOG}
        spderror $? \
            "${SPAR_SUBMIT}/sp_spd --foreground -v 1 $JOBNAME >>${SLOG}"
    fi
fi

if [ "$BUILDER_PID" != "" ]
then
    $SPAR_SUBMIT/sp_postjob "$JOBNAME" $$ -completed
    status=$?
    if [ "$status" != "0" ]
    then
        $ECHO_CMD SPARTAND: sp_postjob "$JOBNAME" $$ -completed  >> ${SLOG}
        $ECHO_CMD SPARTAND: failed $status                       >> ${SLOG}
    fi
fi
