#!/bin/bash
# Reap leaked PostgreSQL dynamic-shared-memory segments from /dev/shm.
# A segment is leaked when its owning postgres died without cleanup
# (SIGKILL/OOM). Deletes only segments that are BOTH >1h old AND not
# open by any live process. Fail-closed: no lsof -> no deletion.
set -u

command -v lsof >/dev/null || { echo "shm-pg-reaper: lsof missing, refusing to reap" >&2; exit 1; }
[ "$(id -u)" -eq 0 ] || { echo "shm-pg-reaper: must run as root (needs full lsof view)" >&2; exit 1; }

open=$(lsof +D /dev/shm 2>/dev/null | awk 'NR>1{print $NF}' | sort -u) || true

n=0
while IFS= read -r -d '' f; do
  grep -qxF "$f" <<<"$open" && continue
  rm -f -- "$f" && n=$((n+1))
done < <(find /dev/shm -maxdepth 1 -name 'PostgreSQL.*' -type f -mmin +60 -print0)

echo "shm-pg-reaper: deleted $n leaked segments"
