#!/bin/bash
# resubmit.sbatch -- continue the anchor transient from its latest timestep.
#
#   sbatch resubmit.sbatch            # continue to REV_TARGET below
#   REV=5.0 sbatch --export=REV resubmit.sbatch
#
# The run restarts from latestTime, so this is safe to fire whenever the
# previous job stopped -- wall clock, crash, or scancel.  It does not chain
# itself: one job, one decision.
#SBATCH --job-name=prop_cont
#SBATCH --time=24:00:00
#SBATCH --nodes=1
#SBATCH --ntasks=48
#SBATCH --cpus-per-task=1
#SBATCH --mem-per-cpu=1G
#SBATCH --output=cont_%j.out
#SBATCH --error=cont_%j.out
set -u
REV=${REV:-4.0}
RPM=7000
END=$(python3 -c "print(repr($REV*60.0/$RPM))")

echo "host=$(hostname) start=$(date +%F\ %T)  target=${REV} rev  endTime=${END}"
source /cluster/apps/local/env2lmod.sh 2>/dev/null || true
module purge 2>/dev/null || true
module load stack/2024-06 gcc/12.2.0 openmpi/4.1.6 openfoam/2306
cd "$SLURM_SUBMIT_DIR/case" || exit 1

# Pin endTime to the revolution target rather than leaving the 8-revolution
# value the original run carried: the thesis needs 4.0 (periodic from 3.25,
# averaged over the last full revolution) and the cores are wanted elsewhere.
sed -i -E "s|^endTime[[:space:]]+.*;|endTime         ${END};|" system/controlDict
grep -E "^(startFrom|endTime)" system/controlDict

LATEST=$(ls processor0 | grep -E '^[0-9]' | sort -g | tail -1)
echo "restarting from t=${LATEST} ($(python3 -c "print(f'{float('$LATEST')*$RPM/60:.4f}')") rev)"

srun -n 48 pimpleFoam -parallel >> log.pimpleFoam 2>&1
rc=$?
echo "rc=$rc end=$(date +%F\ %T)"
LATEST=$(ls processor0 | grep -E '^[0-9]' | sort -g | tail -1)
echo "reached t=${LATEST} ($(python3 -c "print(f'{float('$LATEST')*$RPM/60:.4f}')") rev)"
