#!/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

HHBLITS_ARG_COV=70
HHBLITS_ARG_QID=60
HHBLITS_ARG_MAXID=98
HHBLITS_ARG_ITER=3
HHBLITS_ARG_EVALUE=1e-10

PVLIB_FORCE=false
PVLIB_PATH=""
PVLIB_DOMID=""
NTHREADS=4
NJOBS=1

function print_usage() {
    echo -en "\n  USAGE: ${CMD_NAME} -i <input_fasta> -d <hhblits_db> -n <lib_name> [options]\n"
    echo -en "\n"
    echo -en "  MANDATORY OPTIONS:\n
    -i, --input <name>\tInput file of domain sequences in FASTA format\n
    -D, --domain-id <name>\tDomain identifier\n
                          \t(e.g., Pfam accession number PF03441)\n
    -d, --db <name>\thhblits database name\n
                   \t(multiple databases may be specified with '-d <name1> -d <name2> ...')\n
    -n, --lib-name <name>\tName of ProfileView library\n" | column -t -s $'\t'
    echo -en "\n"
    echo -en "  OTHER OPTIONS:\n
    -f, --force\tForce the construction of ProfileView's library even if the directory already exists\n
           \tpossibly overwriting previously generated files\n
    -t, --threads <num>\tNumber of threads for each hhblits job (default:${NTHREADS})\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"
    echo -en "  Long options (e.g., --input) are supported only on Linux systems\n\n"
}

# retrieve provided arguments
opts="i:D:d:n:ft:j:hV"
longopts="input:,domain-id:,db:,lib-name:,force,threads:,max-jobs:,help,version,cov:,qid:,max-id:,evalue:,iter:"
if [ $(check_system) = "Linux" ]; then
    ARGS=$(getopt -o "${opts}" -l "${longopts}" -n "${CMD_NAME}" -- "${@}")
    retcode=$?
else
    ARGS=$(getopt "${opts}" $*)
    retcode=$?
fi
if [ ${retcode} -ne 0 ] || [ $# -eq 0 ]; then # do not change the order of this test!
    print_usage
    exit 1
fi
eval set -- "${ARGS}"

declare -a DBNAMES
while [ -n "${1}" ]; do
    case ${1} in
        -i|--input)
            shift
            INPUT_FASTA=${1}
            ;;
        -D|--domain-id)
            shift
            PVLIB_DOMID=${1}
            ;;
        -d|--db)
            shift
            DBNAMES+=(${1})
            ;;
        -n|--lib-name)
            shift
            PVLIB_PATH=${1}
            ;;
        -f|--force)
            PVLIB_FORCE=true
            ;;
        -t|--threads)
            shift
            NTHREADS=${1}
            ;;
        -j|--max-jobs)
            shift
            NJOBS=${1}
            ;;
        -h|--help)
            print_usage
            exit 0
            ;;
        -V|--version)
            print_version
            exit 0
            ;;
        --cov)
            shift
            HHBLITS_ARG_COV=${1}
            ;;
        --qid)
            shift
            HHBLITS_ARG_QID=${1}
            ;;
        --max-id)
            shift
            HHBLITS_ARG_MAXID=${1}
            ;;
        --evalue)
            shift
            HHBLITS_ARG_EVALUE=${1}
            ;;
        --iter)
            shift
            HHBLITS_ARG_ITER=${1}
            ;;
        --)
            shift
            break
            ;;
    esac
    shift
done

# Input parameters validation

if [ ${#DBNAMES[@]} -eq 0 ]; then
    print_error "no hh-suite database provided with the -d|--db parameter"
    exit 1
else
    for db in "${DBNAMES[@]}"; do
        db_dir=$(dirname "$db")
        if [ ! -d "${db_dir}" ]; then
            print_error "hh-suite database path \"${dbn_dir}\" cannot be found"
            exit 1
        fi
    done
fi

if [ -z "${INPUT_FASTA}" ] || [ ! -f ${INPUT_FASTA} ]; then
    print_error "-i|--input file is missing or does not exist"
    exit 1
fi

if [ -z "${PVLIB_DOMID}" ]; then
    print_error "-D|--domain-id parameter is mandatory"
    exit 1
fi

if [ -z "${PVLIB_PATH}" ]; then
    print_error "-n|--name parameter is mandatory"
    exit 1
elif [ "${PVLIB_FORCE}" = false ] && [ -d "${PVLIB_PATH}" ]; then
    print_error "it seems that profileview library \"${PVLIB_PATH}\" already exists; delete its directory or use a different name."
    exit 1
fi

if ! [[ "${NTHREADS}" =~ ^[0-9]+$ ]] || [ ${NTHREADS} -lt 1 ] ; then
    print_warning "-t|--threads parameter should be a positive integer; the default value of 1 will be used."
    NTHREADS=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

check_cmds "hhblits" "reformat.pl" "hmmbuild" "python3"

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

# Create ProfileView library directory
PVLIB_NAME=$(basename "${PVLIB_PATH}")
PVLIB_PREFIX="$(dirname "${PVLIB_PATH}")"/"${PVLIB_NAME}"
mkdir -p ${PVLIB_PREFIX}/{query,a3m,hhm,afa,fas,hmm}
if [ $? -ne 0 ]; then
    print_error "cannot create all library directories"
    exit 1
fi
PVLIB_DIR=$(abspath "${PVLIB_PREFIX}")
PVLIB_QUERY="${PVLIB_DIR}"/query

# First split input fasta file
print_status "splitting input file: ${INPUT_FASTA}"
awk -v queryDir="${PVLIB_QUERY}" '
    BEGIN {
        idstr=""
    }
    /^>/ {
        idstr=substr($1,2)
        gsub(/[^A-Za-z0-9._-]/,"_",idstr)
        printf(">%s\n",idstr) >queryDir"/"idstr".fa"
        next
    }
    idstr!="" {
        print >queryDir"/"idstr".fa"
    }
' "${INPUT_FASTA}"

# Run hhblits on each sequences of the fas directory
#TODO: do not execute hhblits if model had been already built
print_status "building hhblits models"
HHBLITS_DBS=""; for hhdb in "${DBNAMES[@]}"; do HHBLITS_DBS="${HHBLITS_DBS} -d ${hhdb}"; done
for query in "${PVLIB_QUERY}"/*.fa; do
    [ -e "${query}" ] || continue
    queryBase=${query##*/}
    queryName=${queryBase%.fa}
    echo "hhblits ${HHBLITS_DBS} -i ${query} -o stdout -oa3m ${PVLIB_PREFIX}/a3m/${queryName}.a3m -ohhm ${PVLIB_PREFIX}/hhm/${queryName}.hhm -M first -cov ${HHBLITS_ARG_COV} -qid ${HHBLITS_ARG_QID} -id ${HHBLITS_ARG_MAXID} -e ${HHBLITS_ARG_EVALUE} -n ${HHBLITS_ARG_ITER} -cpu ${NTHREADS} -v 0 >/dev/null 2>&1"
done | ${PEXEC_CMD} # left it unquoted!

print_status "formatting a3m files"
for a3m in "${PVLIB_DIR}"/a3m/*.a3m; do
    [ -e "${a3m}" ] || continue
    a3mBase="${a3m##*/}"
    a3mName="${a3mBase%.a3m}"
    afaPath="${PVLIB_DIR}/afa/${a3mName}.afa"
    fasPath="${PVLIB_DIR}/fas/${a3mName}.fas"
    echo "reformat.pl a3m fas ${a3m} ${afaPath} -uc -l 80 -v 0 >/dev/null 2>&1 && reformat.pl a3m fas ${a3m} ${fasPath} -M first -r -uc -l 80 -v 0 >/dev/null 2>&1"
done | ${PEXEC_CMD} # left it unquoted!

print_status "building HMMER models"
for afa in "${PVLIB_DIR}"/afa/*.afa; do
    [ -e "${afa}" ] || continue
    afaBase="${afa##*/}"
    afaName="${afaBase%.afa}"
    hmm="${PVLIB_DIR}/hmm/${afaName}.hmm"
    echo "hmmbuild ${hmm} ${afa} >/dev/null 2>&1"
done | ${PEXEC_CMD} # left it unquoted!

print_status "generating ProfileView library data"

for hmm in "${PVLIB_DIR}"/hmm/*.hmm; do
    [ -e "${hmm}" ] || continue
    awk -v domId="${PVLIB_DOMID}" '$1~/^NAME$/{hmm_name=$2;next} $1~/^LENG$/{hmm_len=$2;next} $1~/^NSEQ$/{hmm_nseq=$2;next} $1~/^HMM$/{ OFS=","; print hmm_name,domId,hmm_nseq,hmm_len }' ${hmm}
done > "${PVLIB_PREFIX}/${PVLIB_NAME}.models.list"

python3 "${SCRIPTS_DIR}"/createHHdict.py --hhm-dir "${PVLIB_DIR}/hhm" --prefix "${PVLIB_DIR}"/${PVLIB_NAME}.hhdict >/dev/null 2>&1
python3 "${SCRIPTS_DIR}"/createHmmerDict.py --hmm-dir "${PVLIB_DIR}/hmm" --prefix "${PVLIB_DIR}"/${PVLIB_NAME}.hmmdict >/dev/null 2>&1

