#!/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="$(basename ${BASH_SOURCE[0]} .sh | sed 's/postproc_//g')"

postproc_help() {
    echo -e "" \
	"${str_help_input}\n" \
	" * Cluster/<todo>.${EXT_CLUSTER}\n" \
	"${str_help_output}\n" \
	" * Cluster/<todo>.${EXT_CLUSTER_MAP}\n" \
	"${str_help_desc}\n" \
	"This postproc plugin create cluster file(s) where all labels are remapped to the original labels.\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_MAP}"
            POSTPROC_TRGS+=( "$ftrg" )
            JOBSUBLBL+=( "$JOBLOGNOSPEC" ) # not sure this is needed
        done
    else
        JOBSUBLBL=( "$JOBLOGNOSPEC" )
        POSTPROC_TRGS=("$DIR_PROJECT_CLUSTER/${PL_TODO_NAME}.${EXT_CLUSTER_MAP}")
    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
    
    _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=""
    for node in ${_NODES[@]}; do
        local ftodo=$DIR_PROJECT_TODO/${node}.todo
        local fog=$DIR_PROJECT_CLUSTER/${node}.$EXT_CLUSTER
        local ftrg=$DIR_PROJECT_CLUSTER/${node}.$EXT_CLUSTER_MAP
        # check if target should be remade
        remake_target "$ftrg" "$fog"
        [[ $? -eq 0 ]] || {
            step_info_msg "skipping $(trim_name $ftrg)"
            continue
        }

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

        debug_msg "adding $ftrg"
        
        # set JOB specs <root,node,nthreads>
        JOBARGS+=( "${fog},${ftrg},$ftodo" )
        JOBLABELS+=( "ogmap-$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_ogmap.sh" "0"

    # check error logs
    if [[ ${#JOBLABELS[@]} -gt 0 ]]; then
        check_error $ec "failed ${STEP_ID}:$POSTPROC_NAME"
        [[ $? -eq 0 ]] || return 1
    fi
    
    step_info_msg "link target files in Results"
    link_results "_orthogroups.txt" $alltrgs
    
    # cleanup
    reset_joblists

    
}
