#!/bin/bash
set -euo pipefail

# Select the session account once; both modes use the same trust and supervisor.
run_as=()
if [ -z "${BEAM_VM_KIOSK:-}" ]; then
  read -r desktop_user < /opt/beam-vm/desktop-user
  # The worker overlays /workspace with a fresh root-owned directory.
  chown "$desktop_user:$desktop_user" /run/beam-desktop /workspace
  desktop_home=$(getent passwd "$desktop_user" | cut -d: -f6)
  export XDG_CONFIG_HOME="$desktop_home/.config"
  export XDG_CURRENT_DESKTOP=ubuntu:GNOME DESKTOP_SESSION=ubuntu XDG_SESSION_TYPE=x11
  export GNOME_SHELL_SESSION_MODE=ubuntu
  export XDG_CONFIG_DIRS="/etc/xdg/xdg-ubuntu:${XDG_CONFIG_DIRS:-/etc/xdg}"
  run_as=(runuser -u "$desktop_user" --)
fi
if [ "${1:-}" = --launch ]; then
  shift
  if [ -f /run/beam-desktop/session-bus ]; then
    read -r DBUS_SESSION_BUS_ADDRESS < /run/beam-desktop/session-bus
    export DBUS_SESSION_BUS_ADDRESS XDG_RUNTIME_DIR=/run/beam-desktop
  fi
  exec "${run_as[@]}" "$@"
fi
"${run_as[@]}" /opt/beam-vm/browser-trust
exec "${run_as[@]}" /opt/beam-vm/kiosk
