#!/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/>.
#
#
# Run given cluster algorithm.
# The command line format is
#   run_cluster.sh <fasta1> <fasta2> ...
#
#--- check if environment is ok -----------------
[ "${LOADED_COMMON_PIPELINE_SH+1}" == "" ] && echo "ERROR $0 : main config has not been loaded" 1>&2 && exit 255
#------------------------------------------------
[ $# -eq 1 ] || fatal_msg "$0 - usage <todo label,nthreads>"
input="$1"
inparr=( $(tokenize "," $input) )
[ ${#inparr[@]} -eq 2 ] || fatal_msg "invalid input ($input) to run_cluster.sh, expected comma separated list <label,N>";

# get args
label="${inparr[0]}"
nt="${inparr[1]}"

# nr of threads, cap it to nr of cores available on the machine
nthreads=$(get_nthreads $nt)

# input/output files
srcext=$(get_cmpext SETBRH)
cmpext=$(get_cmpext CLUSTER)
input=$(get_filename "${DIR_PROJECT_CLUSTER}/${label}.${EXT_BRH}" "$srcext")
outbase="${DIR_PROJECT_CLUSTER}/${label}.${EXT_CLUSTER_RAW}"

# check file existance
check_file "$0" "$input" || exit 255

# check script
[[ -x "$CLUSTER_SCRIPT" ]] || fatal_msg "cluster script not found - script : $CLUSTER__SCRIPT"

# uncompress input file if needed
tmpinp=$(uncompress_file2tmp "$input")
if [[ -n $tmpinp ]]; then
    input="$tmpinp"
    tmp_add_file "$tmpinp"
fi

tmpout=""
tmp_make tmpout "cluster" || exit 255

# run script
(tmp_setup_trap && source "$CLUSTER_SCRIPT" "$input" "$tmpout" "$nthreads")
ec=$?

if [[ $ec -eq 0 ]]; then
    [[ -f "${tmpout}.log" ]] && mv -f "${tmpout}.log" "${outbase}.log"
    compress_sync "$tmpout" "$cmpext" "$outbase" "run_cluster.sh"
    ec=$?
fi
exit $ec
