#!/bin/bash
# alpha-shot-sweep — screenshots are never STORED on this box.
#
# Verification screenshots (headless Chrome over CDP: /root/shot.py & co) are
# looked at once and then they are garbage. They used to land loose in /root and
# stayed forever: 150 images + two shot folders sat under the File Manager's
# "Home & backups" on 2026-10-02. Screenshots now go to /tmp/alpha-shots; this
# sweep (hourly, provisioning/cron/alpha-shot-sweep) removes anything that still
# ends up in /root, plus the Chrome profiles the screenshot runs leave in /tmp.
#
#   alpha-shot-sweep            delete (the cron runs this)
#   alpha-shot-sweep --dry-run  list what would go, delete nothing
#
# Scope is deliberately narrow — images only, and only where screenshots land:
#   • image files directly in /root                       older than 60 min
#   • images inside /root/<dir> whose name has "shot" or
#     "screen" in it (vxshots, blog-screens-pending, …)    older than 60 min
#   • everything in /tmp/alpha-shots                       older than 60 min
#   • /tmp/cdp-profile* Chrome profiles                    older than 1 day
# Nothing else in /root is touched (backups, build trees, templates, dotfiles).
set -u
DRY=0; [ "${1:-}" = "--dry-run" ] && DRY=1
IMG=( \( -iname '*.png' -o -iname '*.jpg' -o -iname '*.jpeg' -o -iname '*.webp' -o -iname '*.gif' \) )
n=0; bytes=0

gone() {   # $1 = path; size counted, then removed (or just listed)
  local b; b=$(du -sb -- "$1" 2>/dev/null | cut -f1)
  n=$((n + 1)); bytes=$((bytes + ${b:-0}))
  if [ "$DRY" = 1 ]; then echo "would remove $1"; else rm -rf -- "$1"; fi
}

while IFS= read -r -d '' f; do gone "$f"; done < <(find /root -maxdepth 1 -type f "${IMG[@]}" -mmin +60 -print0 2>/dev/null)

for d in /root/*; do
  [ -d "$d" ] && [ ! -L "$d" ] || continue
  case "${d##*/}" in *shot*|*screen*) ;; *) continue ;; esac
  while IFS= read -r -d '' f; do gone "$f"; done < <(find "$d" -xdev -type f "${IMG[@]}" -mmin +60 -print0 2>/dev/null)
  # drop the folder once nothing but empty dirs is left in it
  [ "$DRY" = 1 ] || find "$d" -depth -type d -empty -delete 2>/dev/null
done

if [ -d /tmp/alpha-shots ]; then
  while IFS= read -r -d '' f; do gone "$f"; done < <(find /tmp/alpha-shots -type f -mmin +60 -print0 2>/dev/null)
fi
while IFS= read -r -d '' p; do gone "$p"; done < <(find /tmp -maxdepth 1 -type d -name 'cdp-profile*' -mmin +1440 -print0 2>/dev/null)

echo "$([ "$DRY" = 1 ] && echo would-free || echo freed) $bytes bytes in $n item(s)"
