#!/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 rewrite
#    the bty.server URL into a ``--catalog <URL>/catalog.toml`` flag
#    (the bty-web instance serves a TOML catalog there matching the
#    operator's ``--catalog`` URL elsewhere) plus ``--mac MAC`` so
#    the TUI POSTs ``<server>/pxe/<mac>/done`` after a successful
#    flash. The pxe-done base is auto-derived from the catalog URL's
#    scheme+host, so the bty.server cmdline param only needs to be
#    the bty-web instance's base URL.
#
# 2. USB-local: 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
    # Rewrite the bty-web base URL into a --catalog <base>/catalog.toml
    # so the TUI consumes the static TOML view (same code path used
    # for static / oras catalogs). The pxe-done base is auto-derived
    # from the URL's scheme+host inside the TUI.
    CATALOG_URL="${SERVER%/}/catalog.toml"
    ARGS="$ARGS --catalog $CATALOG_URL"
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
