#!/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="ogxml"

postproc_help() {
    echo -e "" \
	"${str_help_input}\n" \
	" * Cluster/<todo>.${EXT_CLUSTER}\n" \
	"${str_help_output}\n" \
	" * Cluster/<todo>.${EXT_CLUSTER_OGXML}\n" \
	"${str_help_desc}\n" \
	"Definition of the format is at http://orthoxml.org/0.3/orthoxml_doc_v0.3.html\n" \
    "This post proc plugin creates a orthoxml cluster file.\n" \
    "If the tree mode it will only compute for the root node.\n" \
	"\n"
}

postproc_conf() {
    reset_joblists

    if (( TREE_ENABLED == 1 )); then
        [[ -f $TREE_INPUT_FILE ]] || step_fatal_msg "missing tree file $TREE_INPUT_FILE"
        local nodes=($($PYTHON3 $DIR_ORTHOLOGER/bin/generate_runs.py -t $TREE_INPUT_FILE -N -k 2>/dev/null))
        for node in ${nodes[@]}; do
            local ftrg="$DIR_PROJECT_CLUSTER/${node}.${EXT_CLUSTER_OGXML}"
            POSTPROC_TRGS+=( "$ftrg" )
            JOBSUBLBL+=( "$JOBLOGNOSPEC" ) # not sure this is needed
        done
    else
        JOBSUBLBL=( "$JOBLOGNOSPEC" )
        POSTPROC_TRGS=("$DIR_PROJECT_CLUSTER/${PL_TODO_NAME}.${EXT_CLUSTER_OGXML}")
    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
}

oxml_nodes() {

    step_info_msg "create orthoxml files for each node"
    [[ $DRY_RUN -eq 0 ]] || return 0
    
    # get all nodes
    [[ -f $TREE_INPUT_FILE ]] || step_fatal_msg "missing tree file $TREE_INPUT_FILE"
    local nodes=($($PYTHON3 $DIR_ORTHOLOGER/bin/generate_runs.py -t $TREE_INPUT_FILE -N -k 2>/dev/null))
    step_info_msg "found ${#nodes[@]} nodes"
    
    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_OGXML
        # check if target should be remade
        remake_target "$ftrg" "$fog"
        [[ $? -eq 0 ]] || {
            step_info_msg "skipping $ftrg"
            continue
        }

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

        step_info_msg "adding $ftrg"
        
        # set JOB specs <root,node,nthreads>
        JOBARGS+=( "${fog},${ftrg},$ftodo" )
        JOBLABELS+=( "ogxml-$node" )
        JOBSUBLBL+=( "$JOBLOGNOSPEC" )
    done
    step_info_msg "start running each node (${#nodes[@]} jobs)"
    if [[ ${#nodes[@]} -eq 0 ]]; then
        step_info_msg "all nodes skipped - nothing to do"
        reset_joblists
        return 0
    fi
    
    # third argument flags that it should NOT call init_step() and step_done()
    step_per_label POSTPROC "${DIR_ORTHOLOGER_BIN}/run_ogxml.sh" "0"

    # check error logs
    if [[ ${#JOBLABELS[@]} -gt 0 ]]; then
        check_error $ec "failed ${STEP_ID}:$POSTPROC_NAME"
        [[ $? -eq 0 ]] || return 1
    fi

    # cleanup
    reset_joblists

}


postproc() {
    # check if dry run
    local label=$PL_TODO_NAME
    local ftree="$NONE_VALUE"
    if (( TREE_ENABLED == 1 )); then
        label=$TREE_ROOT_CLADE
        ftree=$TREE_INPUT_FILE
    fi
    local ftodo=$DIR_PROJECT_TODO/${label}.todo
    
    step_info_msg "create a OrthoXML file from node $label"

    is_dryrun && return 0

    local ec=0
    
    # source and target files
    local fog="$DIR_PROJECT_CLUSTER/${label}.${EXT_CLUSTER}"
    local ftrg="$DIR_PROJECT_CLUSTER/${label}.${EXT_CLUSTER_OGXML}"

    SRCFILES=( "$fog" )
    TRGFILES=( "$ftrg" )
    JOBARGS=( "$fog,$ftrg,$ftodo,$ftree" )
    JOBLABELS=( "ogxml-${label}" )
    JOBSUBLBL=( "$JOBLOGNOSPEC" )
    
    # check if target should be remade
    remake_target "$ftrg" "$fog"
    [[ $? -eq 0 ]] || return 0

    # wait for scheduler
    check_scheduler_status ${#SRCFILES[@]}

    # submit jobs
    run_cmd "${DIR_ORTHOLOGER_BIN}/run_ogxml.sh"
    ec=$?

    # wait if batch
    is_runmode_batch
    if [[ $? -eq 0 ]]; then
        sj_wait || { step_error_msg "aborting step since job id wait failed"; exit 255; }
    fi

    # check error logs
    if [[ ${#JOBLABELS[@]} -gt 0 ]]; then
        check_error $ec "failed ${STEP_ID}:$POSTPROC_NAME"
        [[ $? -eq 0 ]] || return 1
    fi

    # cleanup
    reset_joblists

    link_results ".orthoxml" "$ftrg"
    return 0
}
