#!/usr/bin/bash
# /usr/libexec/arrakis-frame-reaper
#
# Safety net for the connector's own --retention-time. Deletes .gwf files well
# past the retention window, so a retention failure fills the journal with
# warnings rather than filling the filesystem.
#
# Configuration arrives via the environment, from
# /etc/sysconfig/arrakis-frame-connector[-<instance>].
set -euo pipefail

: "${OUTDIR:?not set}"
: "${RETENTION_TIME:=300}"
: "${FRAME_DURATION:=1}"
: "${REAPER_MARGIN:=4}"          # cutoff = RETENTION_TIME * this
: "${REAPER_MIN_AGE_SEC:=600}"   # never reap anything younger than this

[[ -d $OUTDIR ]] || { echo "OUTDIR $OUTDIR does not exist" >&2; exit 0; }

# Cutoff derived from retention unless explicitly overridden.
if [[ -z ${REAPER_AGE_SEC:-} ]]; then
  REAPER_AGE_SEC=$(( RETENTION_TIME * REAPER_MARGIN ))
fi
(( REAPER_AGE_SEC < REAPER_MIN_AGE_SEC )) && REAPER_AGE_SEC=$REAPER_MIN_AGE_SEC

# Expected steady-state file count, for the health report below.
expected=$(( RETENTION_TIME / (FRAME_DURATION > 0 ? FRAME_DURATION : 1) ))

before=$(find "$OUTDIR" -mindepth 1 -maxdepth 1 -type f -name '*.gwf' | wc -l)

# '! -newermt "-N seconds"' == older than N seconds.
mapfile -t reaped < <(
  find "$OUTDIR" -mindepth 1 -maxdepth 1 -type f -name '*.gwf' \
       ! -newermt "-${REAPER_AGE_SEC} seconds" -print -delete
)
n=${#reaped[@]}

if (( n > 0 )); then
  # Reaching this point means --retention-time did not do its job.
  echo "WARNING: reaped $n frame(s) older than ${REAPER_AGE_SEC}s from $OUTDIR;" \
       "connector --retention-time $RETENTION_TIME appears not to be trimming" >&2
  echo "         files before=$before after=$(( before - n ))" \
       "expected~$expected" >&2
else
  after=$before
  # No reaping needed, but still flag a directory drifting well past retention.
  if (( after > expected * 2 && after > 20 )); then
    echo "NOTE: $OUTDIR holds $after frames, expected ~$expected;" \
         "growing but not yet past the ${REAPER_AGE_SEC}s reap cutoff" >&2
  fi
fi

exit 0
