#!/bin/bash
# Runs before the display manager on every boot: set the autologin session
# from /etc/ogc-handheld/boot-session.conf (last, desktop or gamemode).
# Keeps the configured autologin user; on first boot picks the first regular
# user (UID >= 1000).
CONF="/etc/sddm.conf.d/zz-steamos-autologin.conf"
BOOT_CONF="/etc/ogc-handheld/boot-session.conf"

BOOT_SESSION=last
[ -r "$BOOT_CONF" ] && . "$BOOT_CONF"

current="$(sed -n 's/^Session=//p' "$CONF" 2>/dev/null | head -n1)"
case "$BOOT_SESSION" in
    gamemode|gamescope) session="gamescope-session-steam.desktop" ;;
    desktop|plasma)     session="plasmawayland.desktop" ;;
    *)
        # last: keep what the previous session left. "Switch to Desktop"
        # from Game Mode is one-shot, so a reboot goes back to Game Mode.
        case "$current" in
            plasmawayland.desktop)  session="plasmawayland.desktop" ;;
            *)                      session="gamescope-session-steam.desktop" ;;
        esac
        ;;
esac

user="$(sed -n 's/^User=//p' "$CONF" 2>/dev/null | head -n1)"
if [ -z "$user" ] || ! id "$user" >/dev/null 2>&1; then
    user="$(getent passwd | awk -F: '$3>=1000 && $3<60000 {print $1; exit}')"
fi
[ -n "$user" ] || exit 0   # no user yet: SDDM shows the greeter

exec /usr/bin/steamos-polkit-helpers/steamos-set-autologin "$session" "$user"
