#!/bin/sh
# Bake ONE mail-template thumbnail outside php-fpm.
#
# WHY IT NEEDS root: php-fpm runs with PrivateDevices=yes, so headless Chrome
# cannot start from a web request at all. systemd-run gives it a fresh namespace.
#
# ⚠️ The path here was WRONG for a long time (lib/thumbs-warm.php; the file is at
# lib/content/thumbs-warm.php), so every on-demand bake silently did nothing —
# which is why a brute-force */5 cron over EVERY template existed to paper over
# it. Fix the path, not the symptom.
#
# ⚠️ CPU containment is the point of the properties below. A thumbnail must
# never compete with the panel, the VPN or a customer's site:
#   CPUQuota=40%           at most 40% of ONE core, enforced by the kernel
#   Nice=19                last in line for whatever is left
#   IOSchedulingClass=idle never stalls real disk work
#   MemoryMax=768M         a runaway renderer is killed, not the box
#   RuntimeMaxSec=90       a wedged Chrome cannot outlive its usefulness
id=$(printf "%s" "$1" | tr -cd "a-zA-Z0-9_")
[ -z "$id" ] && exit 1

exec systemd-run --quiet --collect --uid=www-data --gid=www-data \
  --property=CPUQuota=40% \
  --property=Nice=19 \
  --property=IOSchedulingClass=idle \
  --property=MemoryMax=768M \
  --property=RuntimeMaxSec=90 \
  /usr/bin/php /var/www/alpha/lib/content/thumbs-warm.php "$id"
