#!/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 2 ]] || fatal_msg "usage: $0 <fasta file> <output base>"

[[ -x "$EXE_DIAMOND" ]] || fatal_msg "missing diamond executable on <$(uname -a)>"
[[ ${ALIGNMENT_LABEL} != "DIAMOND" ]] && fatal_msg "alignment is NOT diamond"

# input
inpf="$1"
outbase="$2"
tmpfile=

# check input file
check_file "$0" "$inpf" || fatal_msg "diamond input is not valid [ $inpf ]"

# get dir name and base name of input file
dname=$(dirname  "$outbase")
bname=$(basename "$outbase")

# run diamond
ec=0
{
    #tmp_inpf=""
    ## remove comments
    #tmp_make tmp_inpf  diamond
    #grep -v '^#' "$inpf" > "$tmp_inpf"
    
    # diamond seems to misbehave on occasion... ensure it runs using ONE thread
    export OMP_NUM_THREADS=1
    startdate=$(date)
    tA=$(time_msec)
    print_header "diamond makedb --threads 1 --in $inpf -d ${dname}/${bname}" "$startdate"
    "$EXE_DIAMOND" makedb --threads 1 --in <(grep -v '^#' "$inpf") -d "${dname}/${bname}"
    ec=$?
    dT=$(delta_time $tA)
    print_footer "$dT"
    ####cp -v "$tmp_inpf" "$tmp_inpf".0
    
} >& "${dname}/${bname}.$EXT_DB_LOG"

# check error code and clean up
if [[ $ec -ne 0 ]]; then
    echo "=================FORMATDB DIAMOND FAILED=============="
    echo "Error log at:"
    echo "${dname}/${bname}.$EXT_DB_LOG"
    echo "======================================================"
    rm -f "${dname}/${bname}.${EXT_DB}"
    fatal_msg "failed formatdb diamond (ec=$ec) for input file: $inpf"
fi

