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

postproc_help() {
    echo -e "" \
	"${str_help_input}\n" \
	" * Cluster/<todo>.og\n" \
	"${str_help_output}\n" \
	" * Cluster/<todo>.*dist*\n" \
	"${str_help_desc}\n" \
	"This post proc plugin retrieves stats on cluster species patterns.\n" \
	""
}

postproc_conf() {
    SRCFILES=()
    JOBARGS=()
    JOBLABELS=( "dist" )
    JOBSUBLBL=( "$JOBLOGNOSPEC" )

    local ogfile="$DIR_PROJECT_CLUSTER/${PL_TODO_NAME}.$EXT_CLUSTER"
    POSTPROC_TRGS=("${ogfile}.dist" "${ogfile}.dist_count" "${ogfile}.dist_111-og-ids")

    # 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

    # input file
    SRCFILES=( "${DIR_PROJECT_CLUSTER}/${PL_TODO_NAME}.${EXT_CLUSTER}" )
    JOBARGS=( "${SRCFILES[@]}" )

    # output will be several .dist files - no check here
    # could use mask_ok_sources here...

    # check scheduler
    check_scheduler_status 1

    # run dist count
    run_cmd "${DIR_ORTHOLOGER_BIN}/run_distcount.sh"
    local ec=$?
    if [ $ec -ne 0 ]; then
        step_error_msg "failed to submit job with error code $ec"
        force_remake_new
        return 1
    fi
    
    if is_runmode_batch; then
        sj_wait $STEP_ID || { step_error_msg "aborting step since job id wait failed"; return 255; }
    fi

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

    return 0
}
