#!/usr/bin/env bash
# Run a command as root from inside an agent sandbox, when the owner has granted
# it by placing the password file. No file, no root — there is no standing grant.
#
# The naive form does not work: agent tool processes carry the kernel's
# no_new_privs flag, so sudo/pkexec/run0 all refuse before authenticating.
# systemd-run asks the user manager to spawn a fresh process, which does not
# inherit that flag; PATH is set explicitly because the spawned process starts
# from the manager's environment, not the caller's.
#
# usage: deck-sudo <command> [args...]
set -euo pipefail

PASSFILE="${DECK_SUDO_PASSFILE:-$HOME/stupid.user}"

die() { echo "deck-sudo: ERROR: $*" >&2; exit 1; }

[[ $# -ge 1 ]] || die "usage: deck-sudo <command> [args...]"
[[ -r "$PASSFILE" ]] || die "password file not readable: $PASSFILE"
command -v systemd-run >/dev/null 2>&1 || die "systemd-run not found"

printf -v quoted '%q ' "$@"

systemd-run --user --pipe --wait --collect -q \
  --setenv=PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \
  --setenv=DECK_SUDO_PASSFILE="$PASSFILE" \
  /bin/sh -c '
    read -r pw < "$DECK_SUDO_PASSFILE" || exit 1
    printf "%s\n" "$pw" | exec sudo -S -p "" '"$quoted"'
  '
