#!/bin/bash
# Author: José Antonio Manso García
# License: CC BY-NC 4.0
# This script is licensed under the Creative Commons Attribution-NonCommercial 4.0 International License.
# It may not be used for commercial purposes without explicit permission from the author.
# More info: https://creativecommons.org/licenses/by-nc/4.0/

# Enter input parameters
echo "Enter the receptor file name (including .pdbqt extension, e.g., 2q5k_for_docking.pdbqt)"
read receptor_file

echo "Enter the exhaustiveness value:"
read exhaustiveness

echo "Enter the number of modes (num_modes):"
read num_modes

echo "Enter the energy range:"
read energy_range

echo "Enter the number of CPUs to use:"
read cpu

echo "Is the library an FDA library of compounds? (yes/no):"
read library_type

# Define directories and input files
WORKDIR="$(pwd)"

if [ "$library_type" == "yes" ]; then
    ligand_dir="$WORKDIR/fda_pdbqt_compounds"
else
    ligand_dir=$(find "$WORKDIR" -maxdepth 1 -type d -name "library_pdbqt_*" | head -n 1)
    if [ -z "$ligand_dir" ]; then
        echo "No custom library directory found. Please ensure the directory exists."
        exit 1
    fi
fi

config_file="$WORKDIR/grid.conf"
output_dir="$WORKDIR/docking_results"
mkdir -p "$output_dir"

echo "Resuming docking for unprocessed ligands..."

# Prepare list of ligands to process (only missing or empty outputs)
ligand_files_to_process=()
for ligand_file in "$ligand_dir"/*.pdbqt; do
    ligand_name=$(basename "$ligand_file" .pdbqt)
    output_file="$output_dir/${ligand_name}_docking.pdbqt"
    if [ ! -s "$output_file" ]; then
        ligand_files_to_process+=("$ligand_file")
    fi
done

total_to_process=${#ligand_files_to_process[@]}
echo "Total compounds to (re)process: $total_to_process"

# Initialize timer and counter
start_time=$(date +%s)
count=0

# Process ligands
for ligand_file in "${ligand_files_to_process[@]}"; do
    if [ -f "$ligand_file" ]; then
        ligand_name=$(basename "$ligand_file" .pdbqt)
        output_file="$output_dir/${ligand_name}_docking.pdbqt"
        log_file="$output_file.log"

        echo "Resuming: Docking $ligand_name ..."
        qvina02 --config "$config_file" --receptor "$receptor_file" --ligand "$ligand_file" \
             --exhaustiveness "$exhaustiveness" --num_modes "$num_modes" \
             --energy_range "$energy_range" --cpu "$cpu" \
             --out "$output_file" > "$log_file" 2>&1

        if [ $? -eq 0 ]; then
            ((count++))
            current_time=$(date +%s)
            elapsed=$((current_time - start_time))

            if [ "$elapsed" -gt 0 ]; then
                per_minute=$(echo "scale=2; $count / ($elapsed / 60)" | bc)
                per_hour=$(echo "scale=2; $per_minute * 60" | bc)
                per_day=$(echo "scale=2; $per_hour * 24" | bc)

                remaining=$((total_to_process - count))
                if (( $(echo "$per_minute > 0" | bc -l) )); then
                    est_minutes_left=$(echo "scale=2; $remaining / $per_minute" | bc)
                    est_seconds_left=$(echo "$est_minutes_left * 60" | bc)
                    est_finish_epoch=$(echo "$current_time + $est_seconds_left" | bc | cut -d'.' -f1)
			if [[ "$OSTYPE" == "darwin"* ]]; then
   				 # macOS
    				est_finish_time=$(date -r "$est_finish_epoch")
			else
   				 # Linux
    				est_finish_time=$(date -d "@$est_finish_epoch")
			fi
		else
                    est_finish_time="calculating..."
                fi

                echo "Docking completed for $ligand_name ($count/$total_to_process)"
                echo "Rate: $per_minute comp/min | $per_hour comp/h | $per_day comp/day"
                echo "Estimated time remaining: ${est_minutes_left:-...} min"
                echo "Estimated finish time: $est_finish_time"
                echo "------------------------------------------------------"
            fi
        else
            echo "Docking failed for $ligand_name, check $log_file"
        fi
    fi
done

echo "Resume docking completed. Results stored in $output_dir"

# Display citation message
echo ""
echo "================================================================="
echo " If you are using this program or its results, please cite:"
echo ""
echo " Method paper:"
echo " Barbosa Pereira, P.J., Ripoll-Rozada, J., Macedo-Ribeiro, S., and Manso, J.A. (2025)."
echo " STAR Protocols 6(4), 104161. https://doi.org/10.1016/j.xpro.2025.104161"
echo ""
echo " Manso, J.A. (2025). Zenodo, https://doi.org/10.5281/zenodo.15577778"
echo ""
echo " Trott, O., and Olson, A.J. (2010). Journal of Computational Chemistry 31, 455–461."
echo " https://doi.org/10.1002/jcc.21334"
echo ""
echo " Alhossary, A., Handoko, S.D., Mu, Y., and Kwoh, C.-K. (2015)."
echo " Bioinformatics 31, 2214–2216. https://doi.org/10.1093/bioinformatics/btv082"
echo "================================================================="

