#!/usr/bin/env bash
set -euo pipefail

usage() {
  cat <<'EOF' >&2
usage: tmp-cleanup [--dry-run] [--quiet]

Cleanup policy:
  - remove top-level /tmp regular files older than 3 days
EOF
}

dry_run=0
quiet=0
while [[ $# -gt 0 ]]; do
  case "$1" in
    --dry-run) dry_run=1 ;;
    --quiet) quiet=1 ;;
    -h|--help) usage; exit 0 ;;
    *) echo "Unknown arg: $1" >&2; usage; exit 2 ;;
  esac
  shift
done

log() {
  if [[ $quiet -eq 0 ]]; then
    echo "$@"
  fi
}

tmp_root='/tmp'
cutoff='-mtime +3'
matched=0
deleted=0

while IFS= read -r -d '' path; do
  matched=$((matched + 1))
  if [[ $dry_run -eq 1 ]]; then
    log "[dry-run] delete $path"
    continue
  fi
  if rm -f -- "$path"; then
    deleted=$((deleted + 1))
  fi
done < <(find "$tmp_root" -mindepth 1 -maxdepth 1 -type f $cutoff -print0 2>/dev/null)

if [[ $dry_run -eq 1 ]]; then
  log "policy dir=$tmp_root older_than=3d matched=$matched"
else
  log "policy dir=$tmp_root older_than=3d matched=$matched deleted=$deleted"
fi
