#!/usr/bin/env bash
#
#  This file is part of ProfileView.
#
#  ProfileView is free software: you can redistribute it and/or modify
#  it under the terms of the CeCILL 2.1 Licence
#
#  ProfileView 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.
#
#  You should have received a copy of the Licence CeCILL 2.1 along
#  with ProfileView. If not, see <https://cecill.info/>.
#


CMD_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}" )" && pwd)
CMD_NAME=$(basename "${BASH_SOURCE[0]}")
SCRIPTS_DIR="${CMD_DIR}"/scripts

# Include common definitions
source "${CMD_DIR}/profileview-common"

# Pressing CTRL-C will stop the whole execution of the script
trap ctrl_c INT; 
function ctrl_c() { exit 5; }

# Definition of functions and global variables specific to this script

INPUT_FASTA=""
PV_LIBPATH=""
PV_SEQDESC=""
PV_OUTPREFIX="out"
PV_TMPDIR=""
PV_CVAR=0.99
PV_KBEST=3
NJOBS=8

PEXEC_CMD="parallel --halt now,fail=1 -j ${NJOBS}"
if ! command -v parallel >/dev/null 2>&1; then
    print_warning "cannot find GNU parallel, all jobs will be run sequentially"
    PEXEC_CMD="/usr/bin/env bash --"
fi

function print_usage() {
    echo -en "\n  USAGE: ${CMD_NAME} -i <input_fasta> -l <profileview_lib> [options]\n"
    echo -en "\n"
    echo -en "  MANDATORY OPTIONS:\n
    -i, --input <name>\tFile containing the sequences to be classified in FASTA format\n
    -l, --lib <name>\tProfileView library name/path\n" | column -t -s $'\t'
    echo -en "\n"
    echo -en "  OTHER OPTIONS:\n
    -k, --k-best <num>\tNumber of best-match models to retain for each sequence (default: ${PV_KBEST})\n
    --cvar <num>\tMinimum explained variance threshold for selecting principal components before the clustering (default: ${PV_CVAR})
                \tThe provided value must be a number in the interval [0,1]\n
    -s, --seq-desc <name>\tInput sequence descriptor file, that is a CSV file containing the follwing fileds:\n
                         \t<sequence_id>,<function_id>,<family_id>,<sequence_length>\n
    -p, --prefix <name>\tPrefix of output files (default: ${PV_OUTPREFIX})\n
    --temp-dir <name>\tTemporary result directory\n
    -j, --max-jobs <num>\tNumber of parallel jobs (default: ${NJOBS})\n
    -h, --help\tPrint this help message\n
    -V, --version\tPrint version\n" | column -t -s $'\t'
    echo -en "\n"
}

# retrieve provided arguments

opts="i:l:k:s:p:j:hV"
longopts="input:,lib:,k-best:,seq-desc:,prefix:,temp-dir:,max-jobs:,cvar:,help,version"
ARGS=$(getopt -o "${opts}" -l "${longopts}" -n "${CMD_NAME}" -- "${@}")
if [ $? -ne 0 ] || [ $# -eq 0 ]; then # the order of this tests is important!
    print_usage
    exit 2
fi
eval set -- "${ARGS}"

declare -a DBNAMES
while [ -n "${1}" ]; do
    case ${1} in
        -i|--input)
            shift
            INPUT_FASTA=${1}
            ;;
        -l|--lib)
            shift
            PV_LIBPATH=${1}
            ;;
        -s|--seq-desc)
            shift
            PV_SEQDESC=${1}
            ;;
        -p|--prefix)
            shift
            PV_OUTPREFIX=${1}
            ;;
        --temp-dir)
            shift
            PV_TMPDIR=${1}
            ;;
        -j|--max-jobs)
            shift
            NJOBS=${1}
            ;;
        --cvar)
            shift
            PV_CVAR=${1}
            ;;
        -h|--help) 
            print_usage
            exit 0
            ;;
        -V|--version) 
            print_version
            exit 0
            ;;
        --)
            shift
            break
            ;;
    esac
    shift
done

# Input parameters validation

if [ -z "${INPUT_FASTA}" ]; then
    print_error "-i|--input parameter is mandatory"
    print_usage
    exit 1
elif [ ! -f "${INPUT_FASTA}" ]; then
    print_error "Input file does not exist: ${INPUT_FASTA}"
    exit 1
fi

if [ -z "${PV_LIBPATH}" ]; then
    print_error "-l|--lib parameter is mandatory"
    print_usage
    exit 1
elif [ ! -d "${PV_LIBPATH}" ]; then
    print_error "ProfileView library not found: ${PV_LIBPATH}"
    exit 1
fi

PV_LIBNAME=$(basename "${PV_LIBPATH}")
PV_LIBDIR=$(abspath "${PV_LIBPATH}")

if [ ! -z "${PV_SEQDESC}" ] && [ ! -f "${PV_SEQDESC}" ]; then
    print_error "Cannot find sequence descriptor file: ${PV_SEQDESC}"
    exit 1
fi

if ! [[ "${NJOBS}" =~ ^[0-9]+$ ]] || [ ${NJOBS} -lt 1 ] ; then
    print_warning "-j|--max-jobs parameter should be a positive integer; the default value of 1 will be used."
    NJOBS=1
fi

if ! [[ "${PV_KBEST}" =~ ^[0-9]+$ ]] || [ ${PV_KBEST} -lt 1 ] ; then
    print_warning "-k|--k-best parameter should be a positive integer; the default value of 3 will be used."
    PV_KBEST=3
fi


if ! [[ "${PV_CVAR}" =~ ^(0(\.[0-9]+)?|\.[0-9]+|1(\.0+)?)$ ]] ; then
    print_warning "--cum-var parameter must be a real number in the interval [0,1]; the default value of 0.99 will be used."
    PV_CVAR=0.99
fi


check_cmds "hmmsearch" "python3" "Rscript"
check_pymodules "ete3" "numpy"
#check_files "${SCRIPTS_DIR}"/{createHHdict.py,createHmmerDict.py,hh_utils.py,pv_utils.py}

# Create temp working directory
if [ -z "${PV_TMPDIR}" ]; then
    PV_TMPDIR=$(mktemp -p "${TMPDIR:-.}" -d pvtmp-XXXXX) || {
        print_error "cannot create temporary directory"
        exit 1
    }
fi
PV_TMPDIR=$(abspath "${PV_TMPDIR}")
if [ ! -d "${PV_TMPDIR}" ] || [ -n "$(ls -A "${PV_TMPDIR}")" ]; then
    print_error "provided path \"${PV_TMPDIR}\" must be an empty directory"
    exit 1
fi
print_status "using temporary directory: ${PV_TMPDIR}"

# Create log file
PV_LOGFILE="${PV_TMPDIR}/profileview-tree_$(date +%Y%m%d_%H%M%S).log"
touch "${PV_LOGFILE}" && print_status "a log file is saved in ${PV_LOGFILE}"

# Possibly create a sequence descriptor file (if not provided)
if [ -z "${PV_SEQDESC}" ]; then
    PV_SEQDESC="${PV_TMPDIR}/sequences.csv"
    print_status "creating temporary sequence descriptor file: ${PV_SEQDESC}"
    awk '
        BEGIN {
            sname=""
            seqlen=0
            OFS=","
        }
        /^>/ {
            if(sname!=""){ print sname,"NA","NA",seqlen }
            sname=substr($1,2)
            seqlen=0
            next
        }
        {
            for(i=1;i<=NF;i++){seqlen+=length($i)}
        }
        END {
            if(sname!=""){ print sname,"NA","NA",seqlen }
        }
    ' "${INPUT_FASTA}" >"${PV_SEQDESC}"
else
    cp "${PV_SEQDESC}" "${PV_TMPDIR}/sequences.csv"
    PV_SEQDESC="${PV_TMPDIR}/sequences.csv"
fi

# Run hmmsearch for each model of the library against the input sequences
print_status "running hmmsearch against input sequences"
HMMSEARCH_RESFILE="${PV_TMPDIR}"/hmmsearch.out.gz
for hmm in "${PV_LIBDIR}"/hmm/*.hmm; do
    [ -e "${hmm}" ] || continue
    hmmBase=${hmm##*/}
    hmmName=${hmmBase%.hmm}
    echo "hmmsearch ${hmm} ${INPUT_FASTA} 2>>${PV_LOGFILE}"
done | ${PEXEC_CMD} | gzip -c >"${HMMSEARCH_RESFILE}"
if [ $? -ne 0 ]; then
    print_error "error during hmmsearch jobs, see log: ${PV_LOGFILE}"
    exit 1
fi

print_status "processing hmmsearch output files"
PV_HMMLIB="${PV_LIBDIR}"/"${PV_LIBNAME}".hmmdict.pgz
PV_SCOREFILE="${PV_TMPDIR}"/hmmsearch.scores
zcat "${HMMSEARCH_RESFILE}" | python3 "${SCRIPTS_DIR}"/parseHMMER.py --hmmer-dict "${PV_HMMLIB}" --seq-db "${PV_SEQDESC}" >"${PV_SCOREFILE}" 2>>"${PV_LOGFILE}"
if [ $? -ne 0 ]; then
    print_error "error during processing of hmmsearch results, see log: ${PV_LOGFILE}"
    exit 1
fi


print_status "filtering sequences"
PV_SEQDESC="${PV_TMPDIR}/sequences.filtered.csv"
awk '/^#/{next} !x[$3]++{OFS=",";print $3,$6,$5,$4}' "${PV_SCOREFILE}" >"${PV_SEQDESC}" 2>/dev/null

print_status "building representation space"
python3 "${SCRIPTS_DIR}"/generateFeatures.py --seq-list "${PV_SEQDESC}" --hmm-list "${PV_LIBDIR}/${PV_LIBNAME}.models.list" --scores "${PV_SCOREFILE}" --prefix "${PV_TMPDIR}"/out -n 20 -k "${PV_KBEST}" 2>>"${PV_LOGFILE}"
if [ $? -ne 0 ]; then
    print_error "error during feature generation, see log: ${PV_LOGFILE}"
    exit 1
fi

print_status "building ProfileView tree"
Rscript --vanilla "${SCRIPTS_DIR}"/clusterSequences.R "${PV_TMPDIR}/out.feat" "${PV_CVAR}" "${PV_TMPDIR}/out.tree" 2>>"${PV_LOGFILE}"
if [ $? -ne 0 ]; then
    print_error "could not create ProfileView tree, see log: ${PV_LOGFILE}"
    exit 1
fi

print_status "finding representative models and generating annotated ProfileView tree"
python3 "${SCRIPTS_DIR}/findReprModels.py" -t "${PV_TMPDIR}/out.tree" -s "${PV_SCOREFILE}" -m "${PV_TMPDIR}/out.used_models.list" -o "${PV_OUTPREFIX}" 2>>"${PV_LOGFILE}"
if [ $? -ne 0 ]; then
    print_error "error during identification of representative models and the construction of the annotated ProfileView tree, see log: ${PV_LOGFILE}"
    exit 1
fi


