#!/usr/bin/env bash
#
# orthologer - Pipeline for deducing orthology from fasta files.
# Copyright (C) 2005-2023 E. Zdobnov lab: F. Tegenfeldt
# <fredrik.tegenfeldt@unige.ch> based on code by E. Kriventseva
#
# This file is part of orthologer.
#
# orthologer is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# orthologer is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with orthologer.  If not, see <http://www.gnu.org/licenses/>.
#
#
# This run a given executable on the cluster.
# It is assumed that this is called from salloc
#
[ $# -lt 1 ] && exit 1

output="slurm-%j.out"

USAGE=\
"Usage: `basename $0` [-o <slurm output> ] program [program-opts]\n\
\n\
       Program must be run within a slurm allocation.\n\
       > salloc `basename $0` <program+opts>\n"

while getopts ho: OPT; do
    case "$OPT" in
	o)      output=${OPTARG}
	        ;;
	h)      echo -e $USAGE >&2
	        exit 0
		;;
	\?)	# getopts issues an error message
		echo -e $USAGE >&2
		exit 255
		;;
    esac
done
if [ ${#SLURM_JOB_ID} -eq 0 ]; then
    echo "error: must be run within a slurm allocation (salloc)"
    exit 255
fi

shift `expr $OPTIND - 1`
script="$1"
shift
script_opts="$*"

test -w `dirname $output`
if [ $? -ne 0 ]; then
    echo "output file not writeable : $output"
    exit 254
fi

if [ ! -f "$script" ]; then
    echo "error: could not find script -> $script"
    exit 253
fi

tmpname="$script"

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
## The code below takes the given script and broadcasts it to all
## the allocated nodes. This did cause problems when the remote node
## was powered down.
#
## Create a temp file based on the script name to be broadcast to the node
## the tmpfile can be removed immediately since we just need the name
#bname=/tmp/${SYS_WHOAMI}_`basename $script`_XXXXXXXX
#tmpname=`mktemp $bname`
#rm -f $tmpname
#
## Broadcast the script and give it the name $tmpname.
## NOTE that the script will unlink itself immediately
## when running and it will hence be invisible on the
## target node.
#err=0
#done=0
#while [ $done -eq 0 ]; do
#    # broadcast script to allocated host(s)
#    # with a 20s time out
#    sbcast -t 20 -f $script $tmpname
#    err=$?
#    if [ $err -eq 0 ]; then
#	    done=1
#    else
#	    [ $err -eq 111 ] || done=1
#    fi
#done
#
## exit if broadcast failed
#[ $err -ne 0 ] && exit $err
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


# run job
srun --output=$output $tmpname $script_opts
err=$?

exit $err
