#!/bin/sh
# Realize the naros-vm desktop policy (NAROS.md §7.4 N5). Runs at image-build configure time in
# the mmdebstrap chroot (no running systemd) — every step is offline-safe.
set -e
[ "$1" = "configure" ] || exit 0

# 1. The narOS `agent` user GDM auto-logs into. uid 501 is in lockstep with the sandbox/agent
#    tiers (the uid ContainerEngine execs as); login shell is the contract nash path.
if ! id -u agent >/dev/null 2>&1; then
  useradd --uid 501 --user-group --create-home --home-dir /home/agent \
    --shell /usr/local/bin/nash agent
fi
for g in video input render sudo; do
  getent group "$g" >/dev/null 2>&1 && usermod -aG "$g" agent || true
done
passwd -l agent >/dev/null 2>&1 || true   # auto-login only, no password

# 2. sudoers drop-in must be 0440 (git can't track that mode).
chmod 0440 /etc/sudoers.d/naros-agent 2>/dev/null || true

# 3. GDM auto-login into the agent's Wayland session, so the host surface sees a live screen.
#    (Debian gdm3 reads /etc/gdm3/daemon.conf; we own the desktop policy, so write it whole.)
mkdir -p /etc/gdm3
cat > /etc/gdm3/daemon.conf <<'GDM'
[daemon]
WaylandEnable=true
AutomaticLoginEnable=true
AutomaticLogin=agent
GDM

# 4. Compile the system dconf defaults (AT-SPI on, scale=1, no idle/lock, geometry ext enabled).
dconf update 2>/dev/null || true

# 5. Boot to the graphical session.
systemctl set-default graphical.target >/dev/null 2>&1 || true

# 6. Skip GNOME's first-run tour so the first host screenshot is a usable desktop.
mkdir -p /home/agent/.config
echo yes > /home/agent/.config/gnome-initial-setup-done
chown -R agent:agent /home/agent/.config 2>/dev/null || true

exit 0
