#!/usr/bin/env bash
# =============================================================================
# .automated_script.sh — Entry point triggered by the archiso live environment
#
# PURPOSE:
#   This script is called by the archiso systemd getty service (or directly
#   from .zlogin) immediately after the root user logs in on the live ISO.
#   It acts as the single decision point that determines whether to run the
#   automated unattended installer or the guided interactive installer.
#
# HOW IT WORKS:
#   archiso's default releng profile ships a .automated_script.sh that starts
#   a graphical session or similar. We replace it with this simpler dispatcher.
#
#   The presence or absence of /answerfile.json is the determining signal:
#     - EXISTS  → machine has been configured for unattended deployment
#                 (answerfile was embedded by build.sh --preconf, or placed
#                 on the live system via another mechanism such as a USB drive).
#     → launch.sh is called in "auto" mode and /answerfile.json is passed as
#       the configuration source for arch-autoinstall.sh.
#
#     - MISSING → this is a standard interactive boot (no pre-configuration).
#     → launch.sh is called in "guided" mode which starts the interactive
#       guided installer after prompting for keyboard layout and action.
#
# WHY exec:
#   Using exec replaces this process with launch.sh rather than spawning a
#   child. This means the PID stays the same and signals propagate correctly.
#   If launch.sh exits, the shell exits too, which is the correct behaviour
#   for an installer that terminates after completing or being cancelled.
# =============================================================================

set -euo pipefail

ANSWERFILE="/answerfile.json"

# Check whether an answerfile was embedded in the ISO (or placed on the live
# system). The answerfile contains all installation parameters as JSON, allowing
# completely unattended installation with zero user interaction.
if [[ -f "$ANSWERFILE" ]]; then
    # Automated mode: pass "auto" as the first arg and the answerfile path as
    # the second. launch.sh will forward these to arch-autoinstall.sh.
    exec /root/launch.sh auto "$ANSWERFILE"
else
    # Guided mode: start the interactive installer. The user will be prompted
    # for keyboard layout and installation action before anything happens.
    exec /root/launch.sh guided
fi
