#!/bin/bash -u
#
# 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/>.
#
#
# Run given aligner algorithm.
# The command line format is
#   run_alignment.sh <label Query>,<label DB>
#
fatal_msg "run_merge_seq_files.sh : OBSOLETE"




#--- check if environment is ok -----------------
[ "${LOADED_COMMON_ORTHODB_SH+1}" == "" ] && echo "ERROR $0 : main config has not been loaded" 1>&2 && exit 255
#------------------------------------------------
[ $# -eq 1 ] || fatal_msg "usage: $0 <extension>"

# extension of files in Sequences
ext="$1"

# compress ext
srcid=$(get_step_depend $STEP_ID)
srccmp=$(get_cmpext $srcid)
trgcmp=$(get_cmpext $STEP_ID )

# output file
output="${DIR_PROJECT_CLUSTER}/${PL_TODO_NAME}.${ext}"
outputcmp="$output$trgcmp"

tmpout=""
tmp_make tmpout "mergeseq"

# grep cmd
grepcmd='grep'
[[ -z $srccmp ]] || grepcmd='zgrep'

# if SELECT then produce this empty file
if [ "$SELECT_LABEL" == "NONE" ]; then
    echo "# No inparalogs from select step since label NONE was used" > $tmpout

else

    # tmp output file
    tmp_make tmpfile ${STEP_ID,,}

    # timer
    startdate=$(date)
    tstart=$(time_sec)

    # merge all files
    # see comment on expected error code above (previous case with grep -v)
    for A in "${PL_TODO_LABELS[@]}"; do
        f=$DIR_PROJECT_SEQUENCES/${A}.${ext}
        has_required_label $A || continue
        ###fz=$(get_filename "$f" "$srccmp")
        v_get_filename fz "$f" "$srccmp"
        $grepcmd -v "^#" "$fz" 
        [ $? -lt 2 ] || step_fatal_msg "failed merging files!"
    done > $tmpfile

    # add header/footer
    dT=$(dtime $tstart)
    add_header_footer "$STEP_ID" "$tmpfile" "$tmpout" "$startdate" "$dT" "simple merge"
    [ $? -lt 2 ] || { step_error_msg "failed adding header/footer!"; exit 255; }
fi


# make sure it has the right compression
compress_sync "$tmpout" "$trgcmp" "$output" "run_merge_seq_files.sh"
chmod 644 "$output"
