#!/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 select_cdhit.sh : main config has not been loaded" 1>&2 && exit 255
#------------------------------------------------

# get args
if [[ $# != 3 ]]; then
    echo "Usage select_cdhit.sh <masked fasta> <cleaned fasta> <output>"
    exit 1;
fi

alltmpfiles=
masked="$1"
cleaned="$2"
output="$3"

check_file "select_cdhit.sh" "$masked"  || exit 255
check_file "select_cdhit.sh" "$cleaned" || exit 255


percid=$(awk "BEGIN{ print $SELECT_PID/100.0 };")

# get cdhit options
opts="-p 1 -d 100 -c $percid $OPTS_CDHIT"

# get cdhit command line
#if [[ "$DATA_TYPE" == "NUCL" ]]; then
#    check_file_exe "select_cdhit.sh" "$EXE_CDHIT_NUCL" || exit 255
#    cmd="$EXE_CDHIT_NUCL"
#elif [[ "$DATA_TYPE" == "PROT" ]]; then
check_file_exe "select_cdhit.sh" "$EXE_CDHIT_PROT" || exit 255
cmd="$EXE_CDHIT_PROT"
#else
#    error_msg "${0} : invalid type ${type}"
#    exit 255
#fi

tmp_make tmpfile cdhit
tmp_add_file ${tmpfile}.clstr
tmp_add_file ${tmpfile}.clstr.filtered
tmp_add_file ${tmpfile}.bak.clstr

(( VERBOSE > 1 )) && tmp_mark_keep "$tmpfile"

# get nr of sequences
nseq=$(grep -c "^>" "$masked")

#--------------------------------------------------------------------------------
# run cdhit on original unmasked fasta - gives inaccurate results on masked data
# this is maybe fixed later???
startdate=$(date)
tA=$(time_msec)
ec=0

if (( nseq > 1 )); then
    # cdhit fails miserably (infinite loop) if just 1 sequence
    debug_msg "select_cdhit: command - $cmd $opts -i $cleaned -o $tmpfile"
    "$cmd" $opts -i "$cleaned" -o "$tmpfile"
    ec=$?
    if [[ $ec -ne 0 ]]; then
        error_msg "select_cdhit.sh : cdhit failed with error code $ec"
        exit 255
    fi
    $PYTHON3 $DIR_ORTHOLOGER_BIN/filter_cdhit.py -c "${tmpfile}.clstr" > "${tmpfile}.clstr.filtered"
else
    msg="empty input"
    # 0 or 1 sequence - reconstruct the output
    # output is same as input
    dT=0
    touch "${tmpfile}"       || fatal_msg "failed touching tmp file $tmpfile"
    touch "${tmpfile}.clstr" || fatal_msg "failed touching tmp file ${tmpfile}.clstr"
    echo "#NO DATA" > "$tmpfile"
    echo "#NO DATA" > "${tmpfile}.clstr"
    
    add_header_footer "select_cdhit.sh" "$tmpfile"         "$output"         "${startdate}" $dT "cd-hit trivial case - $msg"
    [[ $? -eq 0 ]] || exit 255
    add_header_footer "select_cdhit.sh" "${tmpfile}.clstr" "${output}.clstr" "${startdate}" $dT "cd-hit trivial case - $msg"
    [[ $? -eq 0 ]] || exit 255

    # we are done here
    exit 0
fi

dT=$(delta_time $tA)

# get keys in output fasta
tmp_make tmpkeys keys
(( VERBOSE > 1 )) && tmp_mark_keep "$tmpkeys"

grep "^>" $tmpfile | sed 's/>\(\S\+\).*/\1/' > $tmpkeys

###debug_msg "select_cdhit: cd-hit resulted in an output of "$(grep "^>" $tmpfile | wc -l)" sequences"

# cp fasta sequences from masked with labels in cdhit result
tmp_make tmpfile2 cdhit_cp
(( VERBOSE > 1 )) && tmp_mark_keep "$tmpfile2"

$PYTHON3 $DIR_ORTHOLOGER_BIN/cp_fasta_sequences.py --keys "$tmpkeys" --fastaseq "$masked" > $tmpfile2
[[ $? -eq 0 ]] || exit 255

#### on older versions of cdhit this file was created
###[[ -f "${output}.bak.clstr" ]] && mv -f "${tmpfile}.bak.clstr" "${output}.bak.clstr"

#--------------------------------------------------------------------------------
# add header and footer
add_header_footer select_cdhit.sh ${tmpfile2} "$output" "${startdate}" $dT "\"$cmd $opts\""
[[ $? -eq 0 ]] || exit 255

add_header_footer select_cdhit.sh "${tmpfile}.clstr.filtered" "${output}.clstr" "${startdate}" $dT "\"$cmd $opts\""
[[ $? -eq 0 ]] || exit 255

#--------------------------------------------------------------------------------
# set permissions
chmod 644 "$output"
chmod 644 "${output}.clstr"
