#!/bin/sh
# Render ONE Payment Studio invoice to PDF outside php-fpm — and WAIT for it.
#
# 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 scope as
# www-data; --wait hands the caller (an invoice email, a "Download PDF" click)
# the file the moment it exists. The PHP side only asks when its cache misses.
#
# Containment — an invoice PDF must never starve the panel, the VPN or a site:
#   CPUQuota=80%     at most 80% of ONE core, enforced by the kernel
#   Nice=10          everything interactive outranks it
#   MemoryMax=900M   a runaway renderer is killed, not the box
#   RuntimeMaxSec=75 a wedged Chrome cannot outlive its usefulness
# bin/invoice-pdf.php adds a flock (one render at a time) and a 45 s timeout.
id=$(printf "%s" "$1" | tr -cd "a-f0-9" | cut -c1-24)
host=$(printf "%s" "$2" | tr -cd "a-zA-Z0-9.-" | cut -c1-120)
[ -z "$id" ] && exit 1

exec systemd-run --quiet --collect --wait --uid=www-data --gid=www-data \
  --property=CPUQuota=80% \
  --property=Nice=10 \
  --property=MemoryMax=900M \
  --property=RuntimeMaxSec=75 \
  /usr/bin/php /var/www/alpha/bin/invoice-pdf.php "$id" "$host"
