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

MODLIST=""
PV_LIBPATH=""
PV_OUTTREE=""
PV_SEQDESC=""
PV_OUTDIR="out_$(date +%Y%m%d_%H%M%S)"
PV_TMPDIR=""
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} -l <profileview_lib> -m <model-list> [options]\n"
    echo -en "\n"
    echo -en "  MANDATORY OPTIONS:\n
    -l, --lib        <name>\tProfileView library name\n
    -m, --model-list <name>\tFile containing a list of models (one identifier per line)\n
    " | column -t -s $'\t'
    echo -en "\n"
    echo -en "  OTHER OPTIONS:\n
    -o, --out-dir  <name>\tPrefix of output files (default: out_<current-date>)\n
    --temp-dir     <name>\tTemporary result directory\n
    -j, --max-jobs  <num>\tNumber of parallel jobs (default:8)\n
    -h, --help\tPrint this help message and exit\n
    -V, --version\tPrint version and exit\n
    " | column -t -s $'\t'
    echo -en "\n"
}

# retrieve provided arguments

opts="l:m:o:j:hV"
longopts="lib:,models:,out-dir:,temp-dir:,max-jobs:,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
        -l|--lib)
            shift
            PV_LIBPATH=${1}
            ;;
        -m|--models)
            shift
            MODLIST=${1}
            ;;
        -o|--out-dir)
            shift
            PV_OUTDIR=${1}
            ;;
        --temp-dir)
            shift
            PV_TMPDIR=${1}
            ;;
        -j|--max-jobs)
            shift
            NJOBS=${1}
            ;;
        -h|--help) 
            print_usage
            exit 0
            ;;
        -V|--version) 
            print_version
            exit 0
            ;;
        --)
            shift
            break
            ;;
    esac
    shift
done

# Pre-requisites check

check_cmds "hhalign" "python3"
check_pymodules "Bio" "weblogolib" "BitVector"

# Input parameters validation

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 "${MODLIST}" ]; then
    print_error "-m|--model-list parameter is mandatory"
    print_usage
    exit 1
elif [ ! -f "${MODLIST}" ]; then
    print_error "cannot find model list file: ${MODLIST}"
    exit 1
fi

# 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}"

# define model paths
declare -a modlst
while read -r line; do
    if [ -z $line ]; then continue; fi # skip empty lines
    mod_path="${PV_LIBDIR}/hhm/${line}.hhm"
    modlst+=("${mod_path}")
done <<< "$(awk -F, '!/^#/ && NF>0{printf("%s\n",$1)}' "${MODLIST}")"

###################
##### HHALIGN #####
###################

print_status "running hhalign jobs for pairwise comparison of models"
HHALIGN_HHRDIR="${PV_TMPDIR}/hhr"
for query in "${modlst[@]}"; do
    [ -e "${query}" ] || continue
    queryBase=${query##*/}
    queryName=${queryBase%.hhm}
    mkdir -p "${HHALIGN_HHRDIR}/${queryName}"
    for target in "${modlst[@]}"; do
        [ -e "${target}" ] || continue
        targetBase=${target##*/}
        targetName=${targetBase%.hhm}
        [ "${queryName}" = "${targetName}" ] || echo "hhalign -i ${query} -t ${target} -o ${HHALIGN_HHRDIR}/${queryName}/${targetName}.hhr -v 0"
    done
done | ${PEXEC_CMD} >>"${PV_LOGFILE}" 2>>"${PV_LOGFILE}"
if [ $? -ne 0 ]; then
    print_error "error during hhalign jobs, see log: ${PV_LOGFILE}"
    exit 1
fi

# merge hhalign results
print_status "merging hhalign job results"
HHALIGN_RESDIR="${PV_TMPDIR}/hhalign"
mkdir -p "${HHALIGN_RESDIR}"
for query in "${modlst[@]}"; do
    [ -e "${query}" ] || continue
    queryBase=${query##*/}
    queryName=${queryBase%.hhm}
    #mkdir -p "${HHALIGN_HHRDIR}/${queryName}"
    for target in "${modlst[@]}"; do
        [ -e "${target}" ] || continue
        targetBase=${target##*/}
        targetName=${targetBase%.hhm}
        [ "${queryName}" = "${targetName}" ] || cat "${HHALIGN_HHRDIR}/${queryName}/${targetName}.hhr"
    done >"${HHALIGN_RESDIR}/${queryName}.hhr"
done

print_status "generating motifs"
HHDICT="${PV_LIBDIR}/${PV_LIBNAME}.hhdict.pgz"
mkdir -p "${PV_OUTDIR}"
if [ $? -ne 0 ]; then
    print_error "cannot create output directory"
    exit 1
fi
python3 "${SCRIPTS_DIR}/parseHHR.py" --hhm-list "${MODLIST}" --hhm-dict "${HHDICT}" --hhr-dir "${HHALIGN_RESDIR}" --fas-dir "${PV_LIBDIR}/fas" --out-dir "${PV_OUTDIR}" 2>>"${PV_LOGFILE}"

