#!/usr/bin/env bash
set -euo pipefail

# Helper minimale per BastionGuard WebUI.
# Deve essere installato root:root 0755 in /usr/local/sbin e richiamato via sudoers.
# Uso: bastionguard-webui-systemctl user <utente> <show|is-active|is-enabled|start|stop|restart|enable|disable> <unit.service> [Prop...]

if [[ $# -lt 4 || "$1" != "user" ]]; then
  echo "Uso: $0 user <utente> <comando> <unit.service> [Prop...]" >&2
  exit 64
fi

TARGET_USER="$2"
CMD="$3"
UNIT="$4"
shift 4

if [[ ! "$TARGET_USER" =~ ^[A-Za-z_][A-Za-z0-9_-]*[$]?$ ]]; then
  echo "Invalid user" >&2
  exit 64
fi
if ! id "$TARGET_USER" >/dev/null 2>&1; then
  echo "User does not exist: $TARGET_USER" >&2
  exit 67
fi
if [[ ! "$UNIT" =~ ^[A-Za-z0-9@_.:-]+\.service$ ]]; then
  echo "Invalid unit: $UNIT" >&2
  exit 64
fi
case "$UNIT" in
  BastionGuard-*.service|bastionguard-*.service) ;;
  *) echo "Unit not allowed: $UNIT" >&2; exit 64 ;;
esac
case "$CMD" in
  show|is-active|is-enabled|start|stop|restart|enable|disable) ;;
  *) echo "Comando non consentito: $CMD" >&2; exit 64 ;;
esac

UID_NUM="$(id -u "$TARGET_USER")"
RUNTIME_DIR="/run/user/$UID_NUM"
BUS="unix:path=$RUNTIME_DIR/bus"

if [[ ! -d "$RUNTIME_DIR" ]]; then
  echo "Runtime utente non presente: $RUNTIME_DIR" >&2
  exit 69
fi

SYSTEMCTL=(/usr/bin/systemctl --user "$CMD" "$UNIT")
if [[ "$CMD" == "show" ]]; then
  # The WebUI passes only property names, never arbitrary options.
  if [[ $# -eq 0 ]]; then
    set -- ActiveState SubState LoadState UnitFileState MainPID FragmentPath Description
  fi
  for prop in "$@"; do
    if [[ ! "$prop" =~ ^[A-Za-z0-9_]+$ ]]; then
      echo "Invalid property: $prop" >&2
      exit 64
    fi
    SYSTEMCTL+=(-p "$prop")
  done
  SYSTEMCTL+=(--no-pager)
fi

if command -v runuser >/dev/null 2>&1; then
  exec runuser -u "$TARGET_USER" -- env XDG_RUNTIME_DIR="$RUNTIME_DIR" DBUS_SESSION_BUS_ADDRESS="$BUS" "${SYSTEMCTL[@]}"
fi
exec sudo -n -u "$TARGET_USER" env XDG_RUNTIME_DIR="$RUNTIME_DIR" DBUS_SESSION_BUS_ADDRESS="$BUS" "${SYSTEMCTL[@]}"
