#!/usr/bin/env bash
#
# Safety-net cleanup for ExCALIBR job directories.
#
# The primary cleanup mechanism is the in-app periodic loop in api.py
# (_periodic_cleanup_loop), which runs every CLEANUP_INTERVAL_SECONDS
# regardless of job submission activity. This script is a backstop for
# cases where the API process itself is down or its cleanup loop has
# stalled -- it should rarely find anything to do.
#
# Unlike the previous version of this script, it will NOT delete a job
# directory whose recorded pid is still alive: it logs a warning instead
# and leaves the directory in place, so we never delete files out from
# under a running process (that was the source of the "input csv doesn't
# exist" bug -- MAX_RUNTIME enforcement should make this a rare event).
#
# Retention window is read from api.py itself (RETENTION_PERIOD), not
# hardcoded here, so the two can never drift apart.

set -euo pipefail

JOBS_DIR="/var/www/html/ExCALIBR/jobs"
API_PY="/var/www/html/ExCALIBR/backend/api.py"
PYTHON_BIN="/home/llawless/.miniconda3/envs/excalibr310/bin/python3.10"

RETENTION_MIN="$("$PYTHON_BIN" "$API_PY" --retention-minutes)"

find "$JOBS_DIR" -maxdepth 1 -mindepth 1 -type d -mmin "+$RETENTION_MIN" -print0 |
while IFS= read -r -d '' dir; do
    pidfile="$dir/pid"
    if [ -f "$pidfile" ]; then
        pid="$(cat "$pidfile" 2>/dev/null || true)"
        if [ -n "${pid:-}" ] && kill -0 "$pid" 2>/dev/null; then
            logger -t excalibr-cleanup "Skipping $dir: pid $pid still alive past retention window ($RETENTION_MIN min) -- in-app cleanup may have failed"
            continue
        fi
    fi
    rm -rf "$dir"
done