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

if [[ $# -ne 1 ]]; then
    echoerr "usage: run_cmpref.sh <fclus>,<fref>,<ftrg>"
    exit 255
fi

# parse input string
input="$1"
inparr=( $(tokenize "," $input) )
[[ ${#inparr[@]} -eq 3 ]] || { echoerr "usage: run_cmpref.sh <fclus>,<fref>,<ftrg>"; exit 255; }

# set input
fclus=$(trim_name "${inparr[0]}")
fref=$(trim_name "${inparr[1]}")
ftrg=$(trim_name "${inparr[2]}")

# check input files
check_file "run_cmpref.sh" "$fclus" || exit 255
check_file "run_cmpref.sh" "$fref"  || exit 255

# make sure output dir is writeable
dirtrg=$(dirname "$ftrg")
iswriteable "$dirtrg" || fatal_msg "output directory is not writeable by user $SYS_WHOAMI -> $dirtrg"

# cmpref tool
cmd=$DIR_BRHCLUS/cmpclus
[[ -x $cmd ]] || fatal_msg "cmpclus cmd not found at $cmd"

# temporary output file
tmp_make tmpout ${PL_TODO_NAME}_cmpref
[[ $? -eq 0 ]] || fatal_msg "failed creating tmp file in $tmpout"

# start timing
startdate=$(date)
tstart=$(time_msec)

opts="--ec 0 --A $fref --B $fclus"
# run cmpref
$cmd mismatch $opts > $tmpout
ec=$?
if [[ $ec -ne 0 ]]; then
    error_msg "cmpref failed with ec = $ec"
    error_msg "-> tmpout : $tmpout"
    error_msg "-> host   : $(hostname)"
    error_msg "-> cmd    : $cmd mismatch $opts"
    cat $tmpout
    exit $ec
fi

# end timing
dT=$(delta_time $tstart)

# add header/footer
add_header_footer run_cmpref.sh $tmpout "$tmpout" "$startdate" $dT "\"${cmd} mismatch $opts\"" || fatal_msg "failed adding final header and footer of file!"

cp -f $tmpout $ftrg
if [[ $? -ne 0 ]]; then
    error_msg "failed copying cmpclus tmp file"
    error_msg "-> tmp output : $tmpout"
    error_msg "-> trg output : $ftrg"
    error_msg "-> host       : `hostname`"
    exit 255
fi

chmod 644 "$ftrg"


