#!/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 postproc_evolrate.sh : 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=("")

postproc_help() {
    echo -e "" \
	"${str_help_input}\n" \
	" * Cluster/<todo>.${EXT_CLUSTER}\n" \
	" * Cluster/<todo>.${EXT_BRH}\n" \
	"${str_help_output}\n" \
	" * Cluster/<todo>.evolrate\n" \
	"${str_help_desc}\n" \
	"This post proc plugin calculates the evolutionary rates for a given todo/tree.\n" \
	""
}

postproc_conf() {
    reset_joblists

    (( TREE_ENABLED == 1 )) || return 0
    [[ -f $TREE_INPUT_FILE ]] || step_fatal_msg "missing tree file $TREE_INPUT_FILE"
    
    # get all branches using TREE_INPUT_FILE as tree
    get_branches_with_children || {
        step_error_msg "postproc_conf: unable to get nodes from $TREE_INPUT_FILE"
        return 255
    }
    local branch=
    for branch in ${_NODES[@]}; do
        local root=${branch%%,*}
        local ftrg="$DIR_PROJECT_CLUSTER/check_${root}.log"
        POSTPROC_TRGS+=( "$ftrg" )
        JOBSUBLBL+=( "$JOBLOGNOSPEC" ) # not sure this is needed
    done
    # 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() {
    step_info_msg "map labels in cluster files"
    [[ $DRY_RUN -eq 0 ]] || return 0
    (( TREE_ENABLED == 0 )) && return 0
    
    local nthreads=${OP_STEP_NTHREADS[$STEP_ID]}

    # get all nodes
    [[ -f $TREE_INPUT_FILE ]] || step_fatal_msg "missing tree file $(trim_name $TREE_INPUT_FILE)"
    get_branches_with_children || {
        step_error_msg "postproc: unable to get nodes from $TREE_INPUT_FILE"
        return 255
    }
    step_info_msg "found ${#_NODES[@]} nodes"
     
    reset_joblists

    local branch=
    for branch in ${_NODES[@]}; do
        local root=${branch%%,*}
        local ftrg="$DIR_PROJECT_CLUSTER/check_${root}.log"
        local fsrc="$DIR_PROJECT_CLUSTER/${root}.og"
        remake_target "$ftrg" "$fsrc" || {
            step_info_msg "skipping $(trim_name $ftrg)"
            continue
        }
        SRCFILES+=( $fsrc )
        TRGFILES+=( $ftrg )
        JOBARGS+=( "${nthreads},$branch" )
        JOBLABELS+=( "checktree-$root" )
        JOBSUBLBL+=( "$JOBLOGNOSPEC" )
    done

    # check nr of jobs to be launched
    if [[ ${#JOBARGS[@]} -eq 0 ]]; then
        step_info_msg "all nodes skipped - nothing to do"
        reset_joblists
        return 0
    fi
    
    step_info_msg "start comparing for each node (${#JOBARGS[@]} jobs)"
    
    # third argument flags that it should NOT call init_step() and step_done()
    step_per_label POSTPROC "${DIR_ORTHOLOGER_BIN}/run_checktree.sh" "0"
    ec=$?
    
    # check error logs
    if [[ ${#JOBLABELS[@]} -gt 0 ]]; then
        check_error $ec "failed ${STEP_ID}:$POSTPROC_NAME"
        [[ $? -eq 0 ]] || return 1
    fi
    
    # cleanup
    reset_joblists
    
    return 0
}
