#!/usr/bin/env bash
# Root-owned, allowlisted helper for Sentinel's remote update commands (v2).
#
# The unprivileged `sentinel` user may reach this ONLY through the four
# exact-argv sudoers lines installed by packaging/install-agent.sh into
# /etc/sudoers.d/sentinel-agent (NOPASSWD, no wildcards, no env passthrough).
# The case arms below are the entire surface: every path is a fixed argv, and
# any other subcommand exits 64 without executing anything. There is
# deliberately no way to pass options through to apt or systemctl.
set -euo pipefail

if [[ $EUID -ne 0 ]]; then
  echo "sentinel-update-helper: must run as root (via sudo)" >&2
  exit 77
fi

subcommand="${1:-}"

case "$subcommand" in
  check)
    # Simulation only — parses the upgradable set without touching the system.
    exec apt-get -s upgrade
    ;;
  update)
    exec apt-get update
    ;;
  upgrade)
    # Conffile policy: keep locally-modified files; only when a file has no
    # local change does --force-confdef fall back to --force-confold (install
    # the maintainer version) — either way dpkg never prompts.
    exec apt-get -y \
      -o Dpkg::Options::=--force-confdef \
      -o Dpkg::Options::=--force-confold \
      upgrade
    ;;
  reboot)
    exec systemctl reboot
    ;;
  *)
    echo "sentinel-update-helper: unknown subcommand '${subcommand}'" >&2
    echo "usage: sentinel-update-helper check|update|upgrade|reboot" >&2
    exit 64
    ;;
esac
