#!/bin/sh
# Creates the kiosk account the whole image is built around.
#
# live-build runs chroot_local-includes BEFORE chroot_local-hooks, so
# /etc/steamtv-agent/config.env (written by build-steam-tv-box-iso.sh) already exists
# here. Sourcing it is why hooks don't need placeholder/sed templating.
set -eu

. /etc/steamtv-agent/config.env

if ! id "$KIOSK_USERNAME" >/dev/null 2>&1; then
  useradd --create-home --shell /bin/bash --comment "Steam TV box kiosk session" "$KIOSK_USERNAME"
fi

# Same list as the thin client, plus `games` — some titles and emulators expect it, and
# `gamemode` needs the user in a group its daemon accepts before it will honour a
# governor request.
for grp in audio video input render dialout netdev plugdev seat _seatd games gamemode bluetooth; do
  if getent group "$grp" >/dev/null 2>&1; then
    adduser "$KIOSK_USERNAME" "$grp" >/dev/null
  fi
done

# No password is baked in: the account is locked so it can never be used to log in
# remotely, while the physical console still autologins via greetd.
passwd --lock "$KIOSK_USERNAME" >/dev/null

adduser "$KIOSK_USERNAME" sudo >/dev/null

# Passwordless sudo is a deliberate call, not laziness: this image autologins to an
# unattended interactive Sway session at the physical console, so anyone standing in
# front of the machine already has the equivalent of a root shell. Requiring a password
# here would buy nothing while making the locked account unadministrable. The
# boundaries that actually matter are the wayvnc password and key-only SSH below.
cat > "/etc/sudoers.d/010-${KIOSK_USERNAME}" <<EOF
${KIOSK_USERNAME} ALL=(ALL) NOPASSWD: ALL
EOF
chmod 0440 "/etc/sudoers.d/010-${KIOSK_USERNAME}"

mkdir -p /etc/ssh/sshd_config.d
cat > /etc/ssh/sshd_config.d/10-steam-tv-box.conf <<'EOF'
PermitRootLogin no
PasswordAuthentication no
KbdInteractiveAuthentication no
PubkeyAuthentication yes
EOF

if [ -d "/home/${KIOSK_USERNAME}/.ssh" ]; then
  chmod 700 "/home/${KIOSK_USERNAME}/.ssh"
  [ -f "/home/${KIOSK_USERNAME}/.ssh/authorized_keys" ] && \
    chmod 600 "/home/${KIOSK_USERNAME}/.ssh/authorized_keys"
fi

# Games are large and this box has a real disk, so the library lives outside the live
# image's writable overlay by convention — see hosts/steam-tv-box/README.md for
# mounting a games disk here. Created either way so Steam's own first-run path exists.
mkdir -p "/home/${KIOSK_USERNAME}/Games"

chown -R "${KIOSK_USERNAME}:${KIOSK_USERNAME}" "/home/${KIOSK_USERNAME}"

systemctl enable ssh >/dev/null 2>&1 || true
