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

    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_conf: unable to get nodes from $TREE_INPUT_FILE"
            return 255
        }
        for node in ${_NODES[@]}; do
            local ftrg="$DIR_PROJECT_CLUSTER/${node}.evolrate"
            POSTPROC_TRGS+=( "$ftrg" )
            JOBSUBLBL+=( "$JOBLOGNOSPEC" ) # not sure this is needed
        done
    else
        JOBSUBLBL=( "$JOBLOGNOSPEC" )
        POSTPROC_TRGS=("$DIR_PROJECT_CLUSTER/${PL_TODO_NAME}.evolrate")
    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() {

    step_info_msg "map labels in cluster files"
    [[ $DRY_RUN -eq 0 ]] || return 0

    local nthreads=${OP_STEP_NTHREADS[$STEP_ID]}

    _NODES=()
    if (( TREE_ENABLED == 0 )); then
        # no tree - a single node given by PL_TODO
        _NODES=( $PL_TODO_NAME )
    else
        # get all nodes
        [[ -f $TREE_INPUT_FILE ]] || step_fatal_msg "missing tree file $(trim_name $TREE_INPUT_FILE)"
        get_internal_nodes || {
            step_error_msg "postproc: unable to get nodes from $TREE_INPUT_FILE"
            return 255
        }
        step_info_msg "found ${#_NODES[@]} nodes"
    fi
     
    reset_joblists
    local node=""
    local ftodoArr=()
    for node in ${_NODES[@]}; do
        ftodoArr+=(${node}.todo)
    done
    # get sorted todo list (by increasing nr of labels)
    cd $DIR_PROJECT_TODO
    local ftodoSorted=($(ls -Sr ${ftodoArr[@]}))
    cd -
    local ftodo=""
    local ec=0
    for ftodoBase in ${ftodoSorted[@]}; do
        node=$(file_basename "$ftodoBase")
        local ftodo="$DIR_PROJECT_TODO/$ftodoBase"
        local fclus="$DIR_PROJECT_CLUSTER/${node}.$EXT_CLUSTER"
        local fbrh="$DIR_PROJECT_CLUSTER/${node}.$EXT_BRH"
        local ftrg="$DIR_PROJECT_CLUSTER/${node}.evolrate"
        # use full todo file to define pairs
        local fpair="$ftodo"
        [[ -f $fbrh ]] && fpair="$fbrh"
        
        # check if target should be remade
        remake_target "$ftrg" "${fclus}:${fpair}"
        [[ $? -eq 0 ]] || {
            step_info_msg "skipping $(trim_name $ftrg)"
            continue
        }

        SRCFILES+=($fclus)
        TRGFILES+=($ftrg)

        debug_msg "adding $ftrg"
        
        # set JOB specs <nthreads,clus,pair,ftrg>
        JOBARGS+=( "${nthreads},${fclus},$fpair,$ftrg" )
        JOBLABELS+=( "evolrate-$node" )
        JOBSUBLBL+=( "$JOBLOGNOSPEC" )
    done
        
    if [[ ${#JOBARGS[@]} -eq 0 ]]; then
        step_info_msg "all nodes skipped - nothing to do"
        reset_joblists
        return 0
    fi
    
    step_info_msg "start mapping for each node (${#JOBARGS[@]} jobs)"
    local alltrgs=${TRGFILES[@]}
    
    # third argument flags that it should NOT call init_step() and step_done()
    step_per_label POSTPROC "${DIR_ORTHOLOGER_BIN}/run_evolrate.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
}
