#!/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 <label>"
set -u

tmp_setup_trap

# select create DB tool
cmd=""
fdb=""
if [[ $ALIGNMENT_LABEL == "MMSEQS" ]]; then
    cmd="$EXE_MMSEQS"
    fdb=mmseqs
    
elif [[ $ALIGNMENT_LABEL == "DIAMOND" ]]; then
    cmd="$EXE_DIAMOND"
    fdb=diamond
else
    cmd="$EXE_MAKEBLASTDB"
    fdb=makeblastdb
fi

verbose_info_msg "create DB tool: $fdb"

[[ -x "$cmd" ]] || step_fatal_msg "missing create DB executable <$cmd>"

# get script
script="$DIR_ORTHOLOGER_BIN/formatdb_${fdb}.sh"
[[ -x $script ]] || step_fatal_msg "formatdb script not found <$script>"

# parse input
input="$1"
inparr=( $(tokenize ";" $input) )

nok=0
nerr=0
ec=0

# loop over set of arguments separated by ';'
for args in ${inparr[@]}; do
    echo
    print_separator
    step_info_msg "Starting FORMATDB job <$args>"
    print_separator
    echo

    # input
    fsel="$DIR_PROJECT_SEQUENCES/${args}.$EXT_FASTA_SELECTED"
    [[ -f $fsel ]] || { step_fatal_msg "missing input file $(trim_name $fsel)"; }
    
    # check for end tag
    check_footer "$fsel" || fatal_msg "run_formatdb : missing end tag (#END) in <$(trim_name $fsel)>"

    # run script
    verbose_info_msg "run make DB for $args with script : $script"
    
    #(tmp_setup_trap && source "$script" "$tmpinp" "$tmpinp")
    ( tmp_setup_trap && source "$script" "$fsel" "$fsel" )
    ec=$?
    if [[ $ec -eq 0 ]]; then
        nok=$((nok+1))
    else
        nerr=$((nerr+1))
    fi
    echo
    print_separator
    step_info_msg "Done FORMATDB job <$args>"
    print_separator
done
echo
[ $nerr -eq 0 ] || { info_msg "Completed $nok succesfully and $nerr with errors"; exit 255; }
