#!/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/>.
#
#--- check if environment is ok -----------------
[ "${LOADED_COMMON_PIPELINE_SH+1}" == "" ] && echo "ERROR $0 : main config has not been loaded" 1>&2 && exit 255
#------------------------------------------------



fatal_msg "DISABLED - requires get_todo_lblind() which is also disabled"




if [ $# -ne 1 ]; then
    echo "usage: $0 <species label>,<nthreads>"
    exit 255
fi

# get arguments, CSV list
args=( $(tokenize "," $1) )
[ ${#args[@]} -eq 2 ] || fatal_msg "got wrong nr of tokens in argument (${#args[@]} ${args[@]})"

specA=${args[0]}
nthreads=${args[1]}

# get pair wise dir
pwcdir=$(get_pwc_dir "$specA")

# cluster file
clusfile=$DIR_PROJECT_CLUSTER/${PL_TODO_NAME}.${EXT_CLUSTER}

# check require files/dirs
check_file "$0" "$clusfile"    || exit 255
check_file "$0" "$PL_TODO"     || exit 255
check_dir  "$0" "$DIR_PROJECT" || exit 255
check_dir  "$0" "$pwcdir"      || exit 255

# cmpclus tool
cmd=$DIR_BRHCLUS/cmpclus
[[ -x $cmd ]] || fatal_msg "cmpclus command is not executable $cmd"

# restore TODO arrays (not exported)
###restore_todo_arrays

# find index of specA
indA=$(get_todo_lblind $specA)

# set basic options for cmpclus
# options are
#  --threads <N>
#  --maxeval <E>    maximum evalue allowed in links
#  --A <cluster data>
#  --P <alignment file w.o dir>    multiple args
#  RELGRP related group command
optncpu=""
[ $nthreads -gt 1 ] && optncpu="--threads $nthreads"
opts="$optncpu --partial --maxeval $MAX_EVALUE --A $clusfile"
opts="$opts -D $pwcdir"

# temporary output file
tmp_make tmpout ${PL_TODO_NAME}_relatedog
[ $? -eq 0 ] || fatal_msg "failed creating tmp file in $tmpout"

tmp_make tmpab "ABunzip"
[ $? -eq 0 ] || fatal_msg "failed creating tmp file in $tmpab"


debug_msg "species A  : $specA ($indA)"
debug_msg "nr of spec : $PL_TODO_NLABELS"
debug_msg "starting loop over B"
Nadd=0

# loop over half matrix
# TODO: perhaps do this optionally depending on ALIGNMENT_MATRIX setting
for (( indB=indA+1; indB<PL_TODO_NLABELS; indB++ )); do
    specB=${PL_TODO_LABELS[$indB]}
    debug_msg "Find alignment $specA - $specB"
#    for ext in ${EXT_ALIGN} ${EXT_ALIGN}.gz; do
#        fAB=${specA}_${B}.$ext
#        [[ -f $fAB ]] && break
    #    done
    fAB=$pwcdir/${specA}_${specB}.$EXT_ALIGN
    lbl=$(basename $fAB)
    
    dounzip=0
    [[ -f $fAB ]] || { fAB=${fAB}.gz; dounzip=1; }
    [[ -f $fAB ]] || fatal_msg "missing pairwise file (A,B or B,A) : $fAB"
    if [[ $dounzip -eq 1 ]]; then
        gunzip -c $fAB > $tmpab || fatal_msg "failed uncompressing file $fAB !"
        lbl=$tmpab
    fi
    debug_msg "Add alignment $specA - $specB"
    opts="$opts -P $lbl"
    Nadd=$((Nadd+1))
done
# make sure something is found - fatal exit otherwise
[[ $Nadd -gt 0 ]] || fatal_msg "found 0 files for species $specA"

# complete options
opts="$opts RELGRP"

startdate=$(date)
tstart=$(time_msec)

$cmd $opts >> $tmpout
ec=$?
if [ $ec -ne 0 ]; then
    error_msg "cmpclus failed with ec = $ec"
    error_msg "-> tmpout : $tmpout"
    error_msg "-> host   : `hostname`"
    cat $tmpout
    exit $ec
fi
# job end time
dT=$(delta_time $tstart)

# add header/footer
add_header_footer $0 $tmpout "$tmpout" "$startdate" $dT "\"${cmd} ${opts}\"" || fatal_msg "failed adding final header and footer of file!"

# target file
trgfile=$pwcdir/${specA}_${PL_TODO_NAME}.relog_part

# copy file to target
cp -f "$tmpout" "$trgfile"
if [ $? -ne 0 ]; then
    error_msg "failed copying related og tmp file"
    error_msg "-> tmp output : $tmpout"
    error_msg "-> trg output : $trgfile"
    error_msg "-> host       : `hostname`"
    exit 255
fi

chmod 644 "$trgfile"
