#!/usr/bin/env bash
# Runs the interactive firstboot as the primary user on first boot, then removes
# itself so subsequent boots log in normally. Installed + enabled by archinstall.
set -uo pipefail

# primary human user: UID 1000 if present, else the first normal-range account
USER_NAME="$(id -nu 1000 2>/dev/null || true)"
[ -n "$USER_NAME" ] || USER_NAME="$(getent passwd | awk -F: '$3>=1000 && $3<60000 {print $1; exit}')"
OK=0
if [ -n "$USER_NAME" ] && [ -x /usr/local/bin/firstboot ]; then
    echo
    echo "=== arch-turnkey first-boot setup (Ctrl-C to skip and do it later) ==="
    # Grant the user passwordless sudo for just this run so setup is truly hands-off
    # (archinstall leaves sudo password-gated); removed the moment firstboot returns.
    SUDOERS=/etc/sudoers.d/99-firstboot-nopasswd
    printf '%s ALL=(ALL) NOPASSWD: ALL\n' "$USER_NAME" >"$SUDOERS" && chmod 440 "$SUDOERS"
    su - "$USER_NAME" -c 'exec /usr/local/bin/firstboot' && OK=1
    rm -f "$SUDOERS"
fi

if [ "$OK" = 1 ]; then
    # success: self-remove so this never runs again, then reboot into the session
    systemctl disable firstboot.service 2>/dev/null || true
    rm -f /etc/systemd/system/firstboot.service /usr/local/bin/firstboot-once
    echo ">> Setup complete. Rebooting into your session in 10s (Ctrl-C to cancel)..."
    for i in $(seq 10 -1 1); do printf "\r   %2ds " "$i"; sleep 1; done; echo
    systemctl reboot
else
    # failure: leave the service enabled to retry next boot; drop to a login shell
    echo ">> first-boot setup did not complete. It will retry on next boot,"
    echo "   or run 'firstboot' manually to retry now."
    systemctl start getty@tty1.service 2>/dev/null || true
fi
