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

# define nr of targets - set in postproc_conf
export POSTPROC_NTARGETS=0
export POSTPROC_TRGS=("")
export POSTPROC_NAME="ogstats"

postproc_help() {
    echo -e "" \
	"${str_help_input}\n" \
	" * Cluster/<todo>.og\n" \
	"${str_help_output}\n" \
	" * Cluster/<todo>.og_stats\n" \
	"${str_help_desc}\n" \
	"This plugin runs statclus on the given cluster file(s).\n" \
	""
}

postproc_conf() {
    reset_joblists

    if (( TREE_ENABLED == 1 )); then
        [[ -f $TREE_INPUT_FILE ]] || step_fatal_msg "missing tree file $TREE_INPUT_FILE"
        get_internal_nodes || {
            step_error_msg "postproc: unable to get nodes from $TREE_INPUT_FILE"
            return 255
        }
        for node in ${_NODES[@]}; do
            local ftrg="$DIR_PROJECT_CLUSTER/${node}.${EXT_CLUSTER}_stats"
            POSTPROC_TRGS+=( "$ftrg" )
            JOBSUBLBL+=( "$JOBLOGNOSPEC" ) # not sure this is needed
        done
    else
        JOBSUBLBL=( "$JOBLOGNOSPEC" )
        POSTPROC_TRGS=("$DIR_PROJECT_CLUSTER/${PL_TODO_NAME}.${EXT_CLUSTER}_stats")
    fi
    # get nr of targets - used by step_start in step_postproc() function
    POSTPROC_NTARGETS=${#POSTPROC_TRGS[@]}
}

postproc_cleanup() {
    local f=""
    for f in ${POSTPROC_TRGS[@]}; do
        rmcmd "$f"
    done
}

postproc() {
    # check if dry run
    [[ $DRY_RUN -eq 0 ]] || return 0

    # get all leaves (script in brhclus get_runs...)
    _NODES=()
    local ec=0

    if (( TREE_ENABLED == 0 )); then
        # no tree - a single node given by PL_TODO
        _NODES=( $PL_TODO_NAME )
    else
        # tree - get all nodes
        # check tree file
        [[ -f $TREE_INPUT_FILE ]] || { step_error_msg "missing tree file $TREE_INPUT_FILE"; return 255; }

        # get a list of ALL nodes
        get_internal_nodes || {
            step_error_msg "postproc: unable to get nodes from $TREE_INPUT_FILE"
            return 255
        }
        debug_msg "found ${#_NODES[@]} nodes in the tree"
    fi

    #--------------------------------------------------------------
    # setbrh all nodes
    # reset jobarg arrays
    reset_joblists

    # loop over all nodes and fill job array args
    local leaf=
    for node in ${_NODES[@]}; do
        # set src/target
        local fsrc=$DIR_PROJECT_CLUSTER/${node}.$EXT_CLUSTER
        local fbrh=$DIR_PROJECT_CLUSTER/${node}.$EXT_BRH
        local ftrg=$DIR_PROJECT_CLUSTER/${node}.${EXT_CLUSTER}_stats

        SRCFILES+=("$fsrc")
        TRGFILES+=("$ftrg")

        # set JOB args <src,brh,trg> required by script run_ogstats.sh
        JOBARGS+=( "${fsrc},${fbrh},${ftrg}" )
        JOBLABELS+=( "ogstats-$node" )
        JOBSUBLBL+=( "$JOBLOGNOSPEC" )
    done

    local alltrgs=${TRGFILES[@]}
    
    local ec=0
    step_info_msg "start processing each node (${#nodes[@]} jobs)"

    # third argument flags that it should NOT call init_step() and step_done()
    step_per_label $STEP_ID "${DIR_ORTHOLOGER_BIN}/run_ogstats.sh" "0"
    ec=$?
    [[ $ec -eq 0 ]] || { step_error_msg "failed nodes with ec=$?"; return $ec; }

    step_info_msg "link target files in Results"
    link_results "_stats.txt" $alltrgs
    
    # clear job arrays
    reset_joblists

    return 0
}
