#!/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 <root label,node label,[child extclin,extclout,label1,label2,...],doweak,nthreads>"
[[ $# -eq 1 ]] || fatal_msg "$0 - usage <node label,input,target,[label1,label2,...],doweak,nthreads>"
input="$1"
inparr=( $(tokenize "," $input) )
nargs=${#inparr[@]}

(( nargs > 4 )) || fatal_msg "invalid input ($input) to run_cluster.sh, expected comma separated list <node,input,target[child1,child2,...],doweak,Nthreads>";

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

#---------------------------------------------------------------------------
# get main args
# current node
lblnode="${inparr[0]}"

# input and output files
inputPairData="${inparr[1]}"
targetClus="${inparr[2]}"

#---------------------------------------------------------------------------
# extract the last two args
# nr of threads, cap it to nr of cores available on the machine
# nthreads is always the last argument
nthreads=$(get_nthreads "${inparr[-1]}")

# set doweak flag to 0 or 1
doweak="${inparr[-2]}"
[[ "$doweak" == "0" ]] || doweak="1"

#---------------------------------------------------------------------------
# extract any children - labels
children=()
extclin=$EXT_CLUSTER
extclout=$EXT_CLUSTER_RAW
if (( nargs > 5 )); then
    for ((i=3; i<nargs-2; i++)); do
        children+=(${inparr[i]})
    done
fi
nkids=${#children[@]}
step_info_msg "cluster with $nkids seed clusters"
step_info_msg "input cluster ext = $extclin , output = $extclout"

#---------------------------------------------------------------------------
# OLD: check if splitbrh is enabled
###stepbrh=SETBRH
###extbrh=brh

#---------------------------------------------------------------------------
# input/output files
# full todo filename - use this to get the directory of todo files
###ftodo=$(expand_name "$PL_TODO")
###dirtodo=$(dirname $ftodo)

# set input pairs file name and possibly create it
# use stepid MAKEBRH -> half matrix, excluding diagonal
# name returned in GENERATED_PAIR_FILE
###PAIR_FILE=$dirtodo/${lblnode}.${EXT_PAIRS}
###create_pairwise_file "MAKEBRH" "0" "$lblnode"

# input files
# if kids are present, more than one file is possible
##inputOgs=()    # array of seed clusters
##inputBRH=()    # array of input weak BRHs (clustered as pair/chain)

###inputBRH="${DIR_PROJECT_CLUSTER}/${lblnode}.${EXT_BRH}"
###inputPairData="$GENERATED_PAIR_FILE"
###[[ -f "$inputBRH" ]] && inputPairData="$inputBRH"

check_file "$0" "$inputPairData" || exit 255

# create CSV of input files
inputFiles=""
if (( nkids==0 )); then
    # no kids - just one file
    inputFiles="$inputPairData"
else
    # a CSV of <input cluster>,<input weak brh> pairs
    for kid in ${children[@]}; do
        [[ -z $inputFiles ]] || inputFiles="${inputFiles},"

        infile="${DIR_PROJECT_CLUSTER}/${kid}.$EXT_CLUSTER"
        check_file "$0" "$infile" || exit 255
        inputFiles="${inputFiles}${infile}"

        # BRH files with pairs that were clustered as pairs/chains
        infile="${DIR_PROJECT_CLUSTER}/${kid}.${EXT_WEAK_BRH}"
        check_file "$0" "$infile" || exit 255
        inputFiles="${inputFiles},${infile}"
    done
    inputFiles="${inputFiles},${inputPairData}"
fi

#---------------------------------------------------------------------------
# now ready to call the cluster scripts
#tmpout=""
#tmp_make tmpout "cluster" || exit 255

# second output
#tmpbrh="${tmpout}.$EXT_WEAK_BRH"
#tmp_add_file "$tmpbrh"


# output files
foutog="${DIR_PROJECT_CLUSTER}/${lblnode}.${extclout}"
foutwbrh="-"
[[ "$doweak" == "0" ]] || foutwbrh="${DIR_PROJECT_CLUSTER}/${lblnode}.$EXT_WEAK_BRH"

info_msg "will run cluster script: $CLUSTER_SCRIPT"
# run script
( tmp_setup_trap; source "$CLUSTER_SCRIPT" "$inputFiles" "$targetClus" "$foutwbrh" "$nthreads" )
ec=$?

exit $ec
