#!/usr/bin/env bash
# Run a command under whp-backup.slice (cgroup v2 io.max) so the slice's I/O
# bounds apply to the entire process tree it spawns — mysqldump | pigz, tar
# | pigz, pg_dump | pigz, and any grandchildren. Sits between the crontab's
# flock+timeout wrapper and the actual php worker invocation.
#
# Usage:
#   whp-backup-runner <cmd> [args...]
#
# Why systemd-run --scope (not --service):
#   --scope places the *calling* shell into a new transient scope unit and
#   then execs the target command, so every grandchild inherits the slice's
#   cgroup. --service would daemonize, breaking cron's exit-status reporting
#   and dropping our place in the I/O cgroup mid-flight.
#
# Why flock+timeout stay in the crontab (not here):
#   So the cron-level pile-up guard works even when systemd-run is missing
#   or the slice isn't installed, and so the convention from CLAUDE.md
#   ("per-minute crons MUST be wrapped with flock -n + timeout") is visible
#   at the cron layer where someone reading crontab -l can see it.

set -euo pipefail

if [[ $# -lt 1 ]]; then
    echo "usage: $0 <cmd> [args...]" >&2
    exit 2
fi

exec /usr/bin/systemd-run --scope --quiet --collect \
    --slice=whp-backup.slice \
    --unit="whp-backup-$(date +%s)-$$" \
    -- "$@"
