#!/bin/bash

# Usage: pydelphi_cpu_job.sh <gridtype> <ncpu>
gridtype="$1"       # "cubic" or "cuboidal"
ncpu="$2"           # e.g. 32, 24, 16, 8, 4, 1
runid="$3"

if [[ -z "$gridtype" || -z "$ncpu" ]]; then
    echo "Usage: $0 <gridtype> <ncpu>"
    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

module load anaconda3/2023.09-0
module load cuda/12.3.0  # can keep this even if no GPU used
source $(conda info --base)/etc/profile.d/conda.sh
conda activate py312_pydelphi020

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

# --- 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" # -p creates parent directories if they don't exist
    if [ $? -ne 0 ]; then
        echo "Error: Failed to create directory '$runid'. Aborting."
        exit 1 # Still abort if directory creation itself fails (e.g., permissions)
    fi
fi
# --- End Directory Check ---

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}_trad-${boxtype}-${gridboxparam}-cpu${ncpu}"
    prmfile="${foutprefix}.prm"

    sed "s/__PQR_FILE__/${pqr}/" "$template_file" > "$prmfile"

    /usr/bin/time -v pydelphi-static -p single -P cpu -t "$ncpu" -f "$prmfile" \
        -o "${foutprefix}-f4.csv" -l "$pdb" -v info -S -O \
        > "${foutprefix}-f4.log" 2>&1

    /usr/bin/time -v pydelphi-static -p double -P cpu -t "$ncpu" -f "$prmfile" \
        -o "${foutprefix}-f8.csv" -l "$pdb" -v info -S -O \
        > "${foutprefix}-f8.log" 2>&1
done

