#!/bin/bash                                                                                                                                                                                                                             
 
# Usage: pydelphi_cpu_job.sh <gridtype> <ncpu> <runid>
gridtype="$1"
ncpu="$2"
runid="$3"
 
if [[ -z "$gridtype" || -z "$ncpu" || -z "$runid" ]]; then
    echo "Usage: $0 <gridtype> <ncpu> <runid>"
    exit 1
fi
 
# Assign fixed gridboxparam per gridtype
if [[ "$gridtype" == "cubic" ]]; then
    boxtype="cbc"
    gridboxparam="pf70"
elif [[ "$gridtype" == "cuboidal" ]]; then
    boxtype="cbl"
    gridboxparam="bxm15"
else
    echo "Error: Unknown gridtype '$gridtype'. Allowed: cubic, cuboidal"
    exit 2
fi
 
 
# --- Directory Check and Creation (with warning, then proceed) ---
if [ -d "$runid" ]; then
    echo "Warning: Directory '$runid' already exists. Assuming it belongs to the same batch of runs and proceeding."
else
    echo "Directory '$runid' does not exist. Creating it..."
    mkdir -p "$runid"
    if [ $? -ne 0 ]; then
        echo "Error: Failed to create directory '$runid'. Aborting."
        exit 1
    fi  
fi
# --- End Directory Check ---
 
module load gcc/13.2.0 boost/1.84.0
 
DELPHI_PATH="${PROJECT_HOME}/software/Delphicpp_v8.5.0_Linux.timemodules"
# --- Check ncpu and set the correct executable ---
if [[ "$ncpu" == "1" ]]; then
    EXE=${DELPHI_PATH}/Release/delphicpp_release
else
    EXE=${DELPHI_PATH}/Release_omp/delphicpp_omp_release
fi
# --- End Check ---


template_file="prm.templates/trad-${gridtype}.prm"

export OMP_NUM_THREADS=${ncpu}

for pqr in $(cat ../pqr-file-list); do
    PDB=${pqr//.pqr/}
    pdb=${PDB,,}
    pdb=${pdb//_/-}
    echo "Processing $pdb with ${ncpu} threads and gridboxparam ${gridboxparam}"

    foutprefix="${runid}/${pdb}-cpp-trad-${boxtype}-sc2-${gridboxparam}-cpu${ncpu}"
    prmfile="${foutprefix}.prm"

    sed "s|__PQR_FILE__|${pqr}|g" "$template_file" > "$prmfile"
    /usr/bin/time -v ${EXE} ${foutprefix}.prm > ${foutprefix}-cpu${ncpu}.log 2>&1
    sleep 2

done

