#!/bin/sh
# Run one command as root with whatever this system uses for that: run0 (systemd 256+), else
# sudo, doas, or pkexec. Used by `just install` and friends.
#
#   scripts/as-root python3 session/install.py
#
# run0 starts the command as a transient systemd service: it does not inherit our environment
# (PATH included; only TERM and a few others get through) and it looks the program up in the
# service manager's own PATH. So the program is resolved to an absolute path here first, which
# also makes tools that are only on our PATH (pixi, ~/.moon/bin) work. The working directory is
# kept (run0 keeps it when the target user is root), so relative paths in the arguments are fine.
set -e
[ $# -gt 0 ] || { echo "usage: scripts/as-root COMMAND [ARG...]" >&2; exit 2; }
prog=$(command -v "$1") || { echo "as-root: $1: not found" >&2; exit 127; }
shift
[ "$(id -u)" = 0 ] && exec "$prog" "$@"
# CHANDRA_AS_ROOT picks the tool (run0, sudo, doas or pkexec) instead of the first one found.
for tool in ${CHANDRA_AS_ROOT:-run0 sudo doas pkexec}; do
  command -v "$tool" >/dev/null 2>&1 || continue
  # run0 needs systemd as PID 1 (and systemd 256+); on other inits fall through to sudo/doas.
  [ "$tool" = run0 ] && [ ! -d /run/systemd/system ] && continue
  exec "$tool" "$prog" "$@"
done
echo "as-root: none of run0, sudo, doas or pkexec is available; run this as root: $prog $*" >&2
exit 1
