#!/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_MAKEBLASTDB" ]] || fatal_msg "missing makeblastdb executable on <$(uname -a)>"
[[ ${ALIGNMENT_LABEL} == "MMSEQS"   ]] && fatal_msg "makeblastdb is incompatible with mmseqs executable - BUG - should use mmseqs to create DB"

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

startdate=$(date)
tA=$(time_msec)

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

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

# move there before running makeblastdb
# this is to avoid problems when your working directory (DIR_PROJECT)
# has a space somewhere - makeblastdb cannot handle that situation
cd "$dname"

# run makeblastdb
flog=
tmp_make flog "makeblastdb"
"$EXE_MAKEBLASTDB" -parse_seqids -dbtype "prot" -logfile "$flog" -in "$inpf" -out "$bname"

# check error code and clean up
ec=$?
dT=$(delta_time $tA)

{
    print_header "makeblastdb -parse_seqids -dbtype prot -logfile $flog -in $inpf -out $bname" "$startdate"
    cat "$flog"
    print_footer "$dT"
} > "${bname}.${EXT_DB_LOG}"
rm -f "$flog"

if [[ $ec -ne 0 ]]; then
    mv -f "$flog" "${bname}.${EXT_DB_LOG}"
    echo "=================FORMATDB MAKEBLASTDB FAILED=============="
    echo "Error log at:"
    echo "${dname}/${bname}.$EXT_DB_LOG"
    echo "=========================================================="
    rm -f "${dname}/${bname}.${EXT_DBPRE}"
    fatal_msg "failed makeblastdb (ec=$ec) for input file: $inpf"
fi
                                                                    
cd -
