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

set -u

#--------------------------------
#--- 1. PROCESS ARGUMENTS     ---
#--------------------------------
# get args
[[ $# -eq 4 ]] || fatal_msg "usage: $0 <query file> <DB file> <output> <nthreads>"
query="$1"
dbase="$2"
output="$3"
nthreads=$4

#--------------------------------
#--- 2. CHECK INPUT           ---
#--------------------------------
check_file     "$0" "$query"       || exit 255
check_file     "$0" "$dbase"       || exit 255

#--------------------------------
#--- 3. CHECK REQUIREMENTS    ---
#--------------------------------
# check that formatdb files are there
check_formatdb_files "$query" 0 || exit 255
check_formatdb_files "$dbase" 0 || exit 255

#--------------------------------
#--- 4. SETUP ALIGNMENT CMD     ---
#--------------------------------
# type dependent options
# -m 9 : tsv fmt with header
# -m 8 : tsv fmt without header
#
# -p   : use nucleotides (0) or proteins (1)
# -S   : which strand (nucl) , 1 -> +, 2 -> -, 3 -> both
#
# -M   : substitution matrix
# -G   : gap opening penalty
# -E   : gap extend penalty
#
# -e   : max e-value
# -b   : max nr of alignments to include (unless limited by the evalue)
# -z   : effective Db size rescaling - if 0, then do no rescaling (size reflects the total length of DB - TOTLEN in .stats files)
# -a   : nr of threads

#
optscommon="$OPTS_SWIPE -b $ALIGNMENT_NUMALIGNMENTS -a $nthreads -m 8 -e $MAX_EVALUE"
#if [[ "$DATA_TYPE" == "NUCL" ]]; then
#    # Nucleotides
#    opts="-S 1 -G 5 -E 2 -M NT2 -p 0 $optscommon"
#else
# Proteins
opts="-p 1 $optscommon"
#fi

#--------------------------------
#--- 5. RUN ALIGNMENT           ---
#--------------------------------
# swipe command
cmd="${EXE_SWIPE}"
#"$cmd" -h | grep "effective database" >& /dev/null
#if [[ $? -eq 0 ]]; then
#    # add effective DB size option (as of 2.0.7)
#    effdbsz=$(get_effdbsz)
#    [[ $effdbsz -eq 0 ]] || opts="$opts -z $effdbsz"

#else
#    # do not warn if 0 as that just implies no scaling
#    [[ $ALIGNMENT_EFFDBSZ -eq 0 ]] || warn_msg "swipe of this version ($($cmd -h | head -n 1)) does not support effective DB size scaling"
#fi

# run swipe and output to tmpfile
tmp_make tmpfile swipe1
startdate=$(date)
tA=$(time_msec)

"$cmd" $opts -d "$dbase" -i "$query" > $tmpfile
ec=$?
dT=$(delta_time $tA)
if [[ $ec -ne 0 ]]; then
    error_msg "# Failed SWIPE"
    error_msg "# Error  : $ec"
    error_msg "# Time   : $dT"
    error_msg "# Query  : $query"
    error_msg "# DB     : $dbase"
    error_msg "# Opts   : $opts -d \"$dbase\" -i \"$query\""
    error_msg "# Output : $(uname -n):$tmpfile"
    tmp_mark_keep "$tmpfile"
    tmp_mark_keep "$query"
    tmp_mark_keep "$dbase"
    exit 255
fi

[[ -f $tmpfile ]] || fatal_msg "lost the temp file during run - check automatic cleanup of temp file!"
#--------------------------------
#--- 6. POST-PROCESSING       ---
#--------------------------------
# Save header from swipe output
swipeid=$(grep "^#" $tmpfile | head -n 1)

#
# swipe fmt is the same for PROT and NUCL if -S 1 is used
# Fields: Query id, Subject id, % identity, alignment length, mismatches, gap openings, q. start, q. end, s. start, s. end, e-value, bit score
#         1         2           3           4                 5           6             7         8       9         10      11       12
#
# common output is
#  id1  id2  score  evalue  percentid  start1  end1  start2  end2
#
# remove lcl| before each query id and output what is needed
tmp_make tmpfile2 swipe2
ec=0
#if [[ "$DATA_TYPE" == "NUCL" ]]; then
#    grep -v "^#" "$tmpfile"    | awk '{ sub(/lcl\|/,"",$2); print $1,$2,$12,$11,$3,$7,$8,$9,$10; }' > "$tmpfile2"
#    ec=$?
#else
grep -v "^#" "$tmpfile"    | awk '{ sub(/lcl\|/,"",$2); print $1,$2,$12,$11,$3,$7,$8,$9,$10; }' > "$tmpfile2"
ec=$?
#fi
[[ $ec -eq 0 ]] || { tmp_mark_keep "$tmpfile"; fatal_msg "failed browsing of alignment result file"; }

#--------------------------------
#--- 7. ADD HEADER/FOOTER     ---
#--------------------------------
add_to_top "$tmpfile2" "$tmpfile2" "$swipeid"                                        || fatal_msg "failed adding swipe id to top of file!"
add_to_top "$tmpfile2" "$tmpfile2" "$(common_fmt_header)"                            || fatal_msg "failed adding header to top of file!"
add_header_footer $0 "$tmpfile2" "$tmpfile2" "$startdate" $dT "${cmd} ${opts} -d \"$dbase\" -i \"$query\"" || fatal_msg "failed adding final header and footer of file!"

# copy file to output
cp -f "$tmpfile2" "$output" || { tmp_mark_keep "$tmpfile"; fatal_msg "failed copying swipe output $tmpfile2 to $output"; }

#--------------------------------
#--- 8. CLEANUP               ---
#--------------------------------
chmod 644 "$output"

