#!/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
[[ $# -eq 1 ]] || fatal_msg "usage: $0 <og file>,<trg file>,<todo file>,<tree file>"
input="$1"
IFS="," read -ra inparr <<< "$input"
[[ ${#inparr[@]} -eq 4 ]] || fatal_msg "$0 : unable to split the csv string in 4 - must be comma separated <$input>"

# parse out files
ogfile=${inparr[0]}
trgfile=${inparr[1]}
todofile=${inparr[2]}
treefile=${inparr[3]}

# executable
cmd="${DIR_ORTHOLOGER_BIN}/og2xml.py"

# check files
check_file     "$0" "$ogfile"   || exit 255
check_file     "$0" "$todofile" || exit 255
check_file_exe "$0" "$cmd"      || exit 255

treeopts="-f $ogfile"
if [[ $treefile != "$NONE_VALUE" ]]; then
    check_file  "$0" "$treefile" || exit 255
    treeopts="-w $treefile"
else
    todolbl=$(file_basename $todofile)
    treeopts="$treeopts --label $todolbl"
fi

trgtmp=""
tmp_make trgtmp "ogxml"

cmdline="$cmd $treeopts -p $todofile --mapdir $DIR_PROJECT_RAWDATA --keep --fail -o $trgtmp --squash"

echo "----------------------------------------------------------------------"
echo "run command: $cmdline"
echo "----------------------------------------------------------------------"
echo
# run command
$PYTHON3 $cmdline --taxsep ':' --ncbitaxids
#--scinames
[[ $? -eq 0 ]] || {
    error_msg "og2oxml.py: $cmdline --taxsep ':' --ncbitaxids"
    fatal_msg "og2oxml.py: failed for input file $ogfile"
}
{
    #echo "<?xml version='1.0' encoding='UTF-8'?>"
    cat "$trgtmp"
} > "$trgfile"

rm -f "$trgtmp"
[[ -f "$trgfile" ]] || fatal_msg "og2xml.py failed to produce $trgfile"


link_results "$trgfile"
