#!/bin/sh
# bty-tui-on-tty1: launch bty-tui on tty1 in interactive mode.
#
# Driven by ``bty-tui-on-tty1.service``, gated on
# ``bty.mode=interactive`` via ``ConditionKernelCommandLine``. We're
# the tty1 session in this mode (the unit conflicts with
# ``getty@tty1.service``); systemd hands us /dev/tty1 as stdio.
#
# Two boot scenarios put ``bty.mode=interactive`` on the cmdline:
#
# 1. PXE-tui (server's ``ipxe_tui.j2`` template, ``boot_policy=tui``):
#    cmdline also carries ``bty.server=`` and ``bty.mac=``. We forward
#    those to ``bty-tui --server URL --mac MAC`` so the TUI fetches
#    the catalog from ``GET <server>/images`` and ``POST``s
#    ``<server>/pxe/<mac>/done`` after a successful flash.
#
# 2. USB-local (M19 phase 2): the live-build iso-hybrid bake sets
#    ``bty.mode=interactive`` directly via ``--bootappend-live`` so
#    the same service fires when the operator boots the USB stick
#    on bare metal with no PXE involvement. No ``bty.server`` or
#    ``bty.mac`` is set; we forward no flags and ``bty-tui`` falls
#    back to scanning the local image-root directory.
#
# Cmdline parsing is intentionally simple (tr+sed): bty.* tokens
# never contain spaces, so word-splitting is safe. Mirrors the
# convention in ``bty-flash-on-boot`` which also reads
# ``/proc/cmdline`` directly.

set -eu

CMDLINE=$(cat /proc/cmdline)

# shellcheck disable=SC2086 # word-split is intended for cmdline tokens
SERVER=$(printf '%s\n' $CMDLINE | tr ' ' '\n' | sed -n 's/^bty\.server=//p' | head -1)
# shellcheck disable=SC2086
MAC=$(printf '%s\n' $CMDLINE | tr ' ' '\n' | sed -n 's/^bty\.mac=//p' | head -1)

ARGS=""
if [ -n "$SERVER" ]; then
    ARGS="$ARGS --server $SERVER"
fi
if [ -n "$MAC" ]; then
    ARGS="$ARGS --mac $MAC"
fi

# We're already root in the live env (auto-login + systemd service);
# no sudo needed. ``exec`` so signals from systemd reach bty-tui
# directly.
# shellcheck disable=SC2086 # ARGS is intentionally word-split
exec /usr/local/bin/bty-tui $ARGS
