#!/usr/bin/env bash
# tmpjail-gc — age-based cleanup of jail temp so ./tmp and the global fallback
# cache don't grow forever (real /tmp is tmpfs and self-clears on reboot; these
# are disk-backed and do not). Prunes files untouched for >AGE_DAYS.
#
# Safety: project ./tmp dirs are only pruned when they carry the ".tmpjail"
# marker that tmpjail writes -- a project's OWN ./tmp (used for something else)
# has no marker and is never touched. The marker file itself is always kept.
#
# Config: TMPJAIL_GC_AGE_DAYS (default 7), TMPJAIL_GC_ROOT (default $HOME).
set -euo pipefail

AGE_DAYS="${TMPJAIL_GC_AGE_DAYS:-7}"
ROOT="${TMPJAIL_GC_ROOT:-$HOME}"
CACHE="${HOME}/.cache/agent-tmp"

# 1. Global TMPDIR fallback dir.
if [[ -d "$CACHE" ]]; then
  find "$CACHE" -mindepth 1 -mtime +"$AGE_DAYS" -delete 2>/dev/null || true
fi

# 2. Marker-tagged project ./tmp dirs + their overlay workdirs. Skip heavy trees
#    so the scan stays fast.
while IFS= read -r marker; do
  d="$(dirname "$marker")"
  find "$d" -mindepth 1 -mtime +"$AGE_DAYS" ! -name .tmpjail -delete 2>/dev/null || true
  w="$(dirname "$d")/.tmpjail-work"
  [[ -d "$w" ]] && find "$w" -mindepth 1 -mtime +"$AGE_DAYS" -delete 2>/dev/null || true
done < <(
  find "$ROOT" \
    -type d \( -name node_modules -o -name .git -o -name .cache -o -name .venv \) -prune -o \
    -type f -name .tmpjail -print 2>/dev/null
)
