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

[[ -x "$EXE_MMSEQS" ]] || fatal_msg "missing mmseqs executable on <$(uname -a)>"

#### remove this check as this script is used in POSTPROC:ogmmprof
####[[ ${ALIGNMENT_LABEL} != "MMSEQS" ]] && fatal_msg "alignment is NOT mmseqs"

# input
inpf="$1"
outbase="$inpf"
[[ $# -eq 2 ]] && outbase="$2"
tmpfile=

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

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

# run mmseqsdb
ec=0
{
    # mmseqs seems to misbehave on occasion... ensure it runs using ONE thread
    export OMP_NUM_THREADS=1
    startdate=$(date)
    tA=$(time_msec)
    print_header "mmseqs createdb $inpf ${dname}/${bname}.$EXT_DBPRE" "$startdate"
    "$EXE_MMSEQS" createdb "$inpf" "${dname}/${bname}.$EXT_DBPRE"
    ec=$?
    dT=$(delta_time $tA)
    print_footer "$dT"
} >& "${dname}/${bname}.${EXT_DB_LOG}"

# check error code and clean up
if [[ $ec -ne 0 ]]; then
    echo "=================FORMATDB MMSEQS FAILED=============="
    echo "${dname}/${bname}.${EXT_DB_LOG}"
    echo "====================================================="
    rm -f "${dname}/${bname}.${EXT_DBPRE}.index.*"
    fatal_msg "failed mmseqsdb (ec=$ec) for input file: $inpf"
fi

# newer versions of mmseqs has this dbtype file
# create an empty place holder -> if mmseqs is upgraded, this script may require a re-run
[[ -f "${dname}/${bname}.${EXT_DBPRE}.dbtype" ]] || echo "PLACEHOLDER FOR FUTURE MMSEQS VERSIONS" > "${dname}/${bname}.${EXT_DBPRE}.dbtype"

