#!/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
#------------------------------------------------

# get args
[[ $# -eq 1 ]] || fatal_msg "Usage: $0 <keyA>,<B>,<nthreads>"

# get and check args
input="$1"
inparr=( $(tokenize ";" $input) )

nok=0
nerr=0

# check findbrh extra options
extraopts=""
if [[ $MAKEBRH_NALT -gt 1 ]]; then
    extraopts="--Nalt $MAKEBRH_NALT --fsepmax $MAKEBRH_FSEPMAX"
fi

tmp_make_dir tmpdir "makebrh"        || exit 255
move_files="echo 'move files'"

echo
echo "---> running MAKEBRH nochecks script"
echo

move_files="echo 'move files'"

for args in ${inparr[@]}; do
    
    argsarr=( $(tokenize "," $args) )
    [[ ${#argsarr[@]} -eq 3 ]] || fatal_msg "run_makebrh.sh: invalid input ($input), expected comma separated list <idA0,idB0,N;idA1,idB2,N;...> but got <$input>";

    A="${argsarr[0]}"
    B="${argsarr[1]}"
    nthreads=${argsarr[2]}

    # alt output in tmpdir/<keyA>/A_B.align
    #mkdir -p $tmpdir/$A || {
    #    error_msg "failed creating tmp dir at $tmpdir/$A"
    #    df -h /tmp | tail -n 1 1>&2
    #    fatal_msg "aborting"
    #}
    #tmpout="$tmpdir/$A/${A}_${B}.${EXT_BRH}"
    tmpout="$tmpdir/${A}_${B}.${EXT_BRH}"
    
    # create tmp output
    #tmp_make tmpout "outAB" || exit 255
    
    fAB="${DIR_PROJECT_PWC}/$A/${A}_${B}.${EXT_ALIGN}"
    output="${DIR_PROJECT_PWC}/$A/${A}_${B}.${EXT_BRH}"

    startdate=$(date)
    ec=0
    cmdargs=""
    if [[ $ALIGNMENT_MATRIX -eq 1 ]]; then
        cmdargs="--AB \"$fAB\" $extraopts"
    else
        fBA="${DIR_PROJECT_PWC}/$B/${B}_${A}.${EXT_ALIGN}"
        cmdargs="--AB \"$fAB\" --BA \"$fBA\" $extraopts"
    fi
    # run tool
    {
        print_header "$EXE_FINDBRH $cmdargs"  "$startdate"
        echo "# ALIGNMENT_MATRIX = $ALIGNMENT_MATRIX"
        if (( MAKEBRH_NALT > 1 )); then
            echo "# fuzzy BRHs with N=$MAKEBRH_NALT and fsepmax=$MAKEBRH_FSEPMAX"
        fi
        common_fmt_header
        tA=$(time_msec)
        eval "$EXE_FINDBRH" "$cmdargs"
        ec=$?
        dT=$(delta_time $tA)
        print_footer "$dT"
    } > "$tmpout"

    if [[ $ec -ne 0 ]]; then
        error_msg "$0 : failed finding BRHs for key pair [$A,$B] with error $ec"
        nerr=$((nerr+1))
        continue
    fi
    nok=$((nok+1))
    
    chmod 644 $tmpout
    move_files="$move_files && mv -f $tmpout $output"

    info_msg "Done makebrh job <$A,$B>, exit code = $ec"
done

echo "Moving files"
# move all files
eval $move_files

# rsync files
#cd $tmpdir
#rsync -ah ./ "$DIR_PROJECT_PWC"

[[ $? -eq 0 ]] || { nerr=$((nerr+1)); error_msg "failed moving at least one file"; }
[[ $nerr -eq 0 ]] || { info_msg "Completed $nok succesfully and $nerr with errors"; exit 255; }
info_msg "DONE"

