#!/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/>.
#
#
# This will setup a pipeline environment in a given target directory.
#-------------------------------------------------------------------------------------------------------
# Variable               Default              Description
#-------------------------------------------------------------------------------------------------------
# EXE_PATH               ''                   Additional search path for tools like brhclus, cdhit, ...
# DIR_ORTHOLOGER         <script dir>/..      ORTHOLOGER software root directory, by default uses one up
#                                             relative this scripts directory
# DIR_PROJECT            <current dir>        Project directory
# NTHREADS               <conservative>       The nr of threads available
# NBATCH                 100                  The nr of jobs sent to scheduler
# URL_ORTHODB_API_BASE   'current'            OrthoDB API version ( current, v11 or v12 )
#-------------------------------------------------------------------------------------------------------
#
# It also checks one argument. If given, it is assumed to be a fasta import file
# with labels plus filenames.
#
IMPORT=""
IMPARGS=""
if [[ $# -eq 1 ]]; then
    IMPORT="$1"
    [[ -f "$IMPORT" ]] || { echo "error: given import file is not readable"; exit 255; }
    IMPARGS="-f $IMPORT"
fi

# Additional tool search path
EXE_PATH=${EXE_PATH:=}

# get pipeline dir
DIR_ORTHOLOGER=${DIR_ORTHOLOGER:="$(cd -P "$(dirname "${BASH_SOURCE[0]}")"/../ && pwd)"}

# get the project dir
DIR_PROJECT=${DIR_PROJECT:="$(pwd)"}

# nr of threads (modified below)
NTHREADS=${NTHREADS:=0}

# nr of jobs per batch
NBATCH=${NBATCH:=100}

# enforce colors etc in messages
PRETTY_PRINT=1

# force loading
#unset LOADED_COMMON_BASE_SH
#unset LOADED_COMMON_PIPELINE_SH
#unset LOADED_COMMON_ODB_SH

# load common base
[[ -f "${DIR_ORTHOLOGER}/bin/common_odb.sh" ]] || { echo "FATAL: unable to find common_odb.sh in setup at $DIR_ORTHOLOGER - is it installed?"; exit 255; }
source "${DIR_ORTHOLOGER}/bin/common_odb.sh"

[[ -f "${DIR_ORTHOLOGER}/etc/orthologer_conf.sh" ]] && {
    info_msg "reading global orthologer config at ${DIR_ORTHOLOGER}/etc/orthologer_conf.sh"
    source "${DIR_ORTHOLOGER}/etc/orthologer_conf.sh"
}

# Add URL_ORTHODB_API_VERSION=<version> in etc/orthologer_conf.sh in order to explicitely
# set the API version.
# Valid versions are: v11,v12 and current .
set_orthodb_api

# set/check python
set_python3

# set some Orthologer defaults
export POSTPROC_LABELS=ogmap

# Set nr of threads to a conservative nr depending on the nr of cores and threads available.
# 1. NTHREADS>0 : cap the nr of threads to the nr of threads available
# 2. NTHREADS=0 : if hyperthreading, set NTHREADS = nr of cores
#                 else NTHREADS = nr of cores/2
# Allow NTHREADS to be set before running this script. Default is 0
# if given NTHREADS is not an integer fall back to NTHREADS=0
printf "%d" "$NTHREADS" >& /dev/null || NTHREADS=0

# make the final decision
NTHREADS=$(get_nthreads_conservative $NTHREADS)

# ensure that NBATCH is reasonable
printf "%d" "$NBATCH" >& /dev/null || NBATCH=100
(( NBATCH >= NTHREADS )) || NBATCH=$(( 2*NTHREADS ))

# Run config
info_msg "Setting up orthologer/orthomapper environment"
info_msg "Project directory       : $DIR_PROJECT"
info_msg "OrthoDB API version     : $API_ORTHODB_VERSION"
info_msg "Extra search path       : $EXE_PATH"
info_msg "Max nr of threads       : $NTHREADS"
info_msg "Max nr of jobs in batch : $NBATCH"
info_msg "Import file             : $IMPORT"
EXE_OPTS=""
[[ -n $EXE_PATH ]] && EXE_OPTS="-E $EXE_PATH"
source $DIR_ORTHOLOGER/bin/manage_project.sh -p -s $EXE_OPTS -L "$NTHREADS" -B "$NBATCH" $IMPARGS
[[ $? -ne 0 ]] && { error_msg "failed running configure script!"; exit 255; }


#if [[ $TREE_ENABLED -eq 1 ]]; then
#   echo "Info: setting tree environment"
#   unset LOADED_COMMON_PIPELINE_SH
#    ./orthologer.sh -G || { echo "Error: failed setting up tree environment"; exit 255; }
#fi

info_msg "----------------------------------------------------------------------------"
info_msg
info_msg "Setup run successful."
info_msg
info_msg "Check the pipeline setup:"
info_msg
info_msg "   ./${CMD_PIPELINE} -xp"
info_msg
info_msg "For help, do (note the '.'):"
info_msg
info_msg "   ./${CMD_PIPELINE} -h             # main help"
info_msg "   ./${CMD_PIPELINE} -H .           # extended help"
info_msg "   ./${CMD_PIPELINE} -H .variables  # help on the variables"
info_msg "   ./${CMD_PIPELINE} -H .examples   # various examples"
info_msg
info_msg "Import fasta files given by fasta.txt into an existing project"
info_msg
info_msg "   ./${CMD_PIPELINE} manage -f fasta.txt"
info_msg
info_msg "The file fasta.txt contains one line per file to be imported together with a label:"
info_msg "+fish    /data/fasta/organism.fs"
info_msg "...."
info_msg
info_msg "The '+' before the label implies that the fasta labels should be replaced by"
info_msg "this label plus a number."
info_msg
info_msg "After checking your setup is OK, run all steps using:"
info_msg
info_msg "   ./${CMD_PIPELINE} -r all"
info_msg
