#!/usr/bin/env bash

CYGWIN=0

## This script submit a job

## This version works both for Linux/Mac and Windows under CYGWIN. We
## just have to add the environment

maketemp () {
    mktemp -t inla.remote.XXXXXXXX
}

compress_put="z"
compress_get="z"
## this one is fixed, do not change
SSHDefaultPort=22

if [ "${INLA_DEBUG}XX" != "XX" ]; then
    set -vx
    echo "INLA_PATH $INLA_PATH"
    echo "INLA_HOME $INLA_HOME"
    echo "INLA_SSH_AUTH_SOCK $INLA_SSH_AUTH_SOCK"
    echo "INLA_OS $INLA_OS"
    echo "INLA_CYGWIN_HOME $INLA_CYGWIN_HOME"
    echo "INLA_HGVERSION $INLA_HGVERSION"
    echo "INLA_SUBMIT_ID"
fi

if [ "$INLA_OS" == "windows" ]; then
    INIFILE=$INLA_HOME/.inlarc
    export SSH_AUTH_SOCK="$INLA_SSH_AUTH_SOCK"
    if [ "$INLA_CYGWIN_HOME"XX != "XX" ]; then
	export HOME=$INLA_CYGWIN_HOME
    fi
else
    INIFILE=~/.inlarc
    if [ "$SSH_AUTH_SOCK"XX == "XX" ]; then
	## this is not set, weird, but it might be that a manual setup is used
	export SSH_AUTH_SOCK="$INLA_SSH_AUTH_SOCK"
    fi   
fi

## these are the variables to be set by the user
RemoteINLA="/usr/local/bin/inla"
RemoteHost=inla.math.ntnu.no
RemoteUser=$USER
Port=$SSHDefaultPort
sshArguments="-x -o BatchMode=yes -o TCPKeepAlive=yes -e none"

if [ -r "$INIFILE" ]; then
    if [ "$INLA_OS" == "windows" ]; then
	TMP=$(maketemp)
	tr -d \\015 < "$INIFILE" > $TMP
	source $TMP
	rm -r $TMP
    else
	source "$INIFILE"
    fi
else
    echo -e "\n\n\n$0: No such file $INIFILE"
    echo -e "Run command in R: inla.remote()"
    echo -e "\n\n"
    exit 1
fi

model=$(echo "$@" | awk '{print $NF}')
dir=${model%/*}
rdir=tmp/.inla.remote/inla-job-$(date | tr '[ :]' -)---$RANDOM$RANDOM
args=$(echo "$@" | awk '{$NF="";print}')

verbose=0
if $(echo $args | awk '$0 ~ /(^|[ \t])-v($|[ \t])/{exit 0};{exit 1}'); then
    {
	verbose=1
	echo -e "\tSubmit job [$INLA_SUBMIT_ID] at host $RemoteHost" 
    } 1>&2
fi

TMP=$(maketemp)
{
    echo "inladatadir=data.files"
    echo "inlaresdir=results.files"
    egrep -v '^(inladatadir|inlaresdir)' $model 
} > $TMP
mv -f $TMP $model

## finally, do the job...  Do this in two steps, as it seems that for
## long jobs the pipe gets terminated.
cd $dir > /dev/null

tar cfm$compress_put - . 2>/dev/null | ssh -p$Port $sshArguments $RemoteUser@$RemoteHost "\
    mkdir -p $rdir; \
    cd $rdir; \
    echo $INLA_SUBMIT_ID > jobid; \
    echo > working; \
    tar xfm$compress_put - 2>/dev/null ; \
    { rm -f working; $RemoteINLA $args -v Model.ini && echo > done; } </dev/null > Logfile.txt 2>&1 &" &
