#!/bin/bash
set -e

# Unblock WiFi and turn the radio on before initial-setup runs, so its NetworkSpoke
# (and the desktop afterwards) can see/scan networks. The Switch's BCM4356A3 comes up
# rfkill soft-blocked, which is why WiFi could not be configured in initial-setup.
# Best-effort: must never block firstboot, so guard and swallow failures under set -e.
command -v rfkill >/dev/null 2>&1 && rfkill unblock wifi 2>/dev/null || true
command -v nmcli  >/dev/null 2>&1 && nmcli radio wifi on 2>/dev/null || true

if [[ -e /boot/switchroot/firstboot ]]; then
    # Read literal assignments; removable-media configuration is not shell code.
    mapfile -t credentials < <(python3 - /boot/switchroot/firstboot <<'PYCODE'
import pathlib, re, shlex, sys
try:
    entries = shlex.split(pathlib.Path(sys.argv[1]).read_text(), comments=True)
    values = dict(entry.split("=", 1) for entry in entries)
    username, password = values["USERNAME"], values["PASSWORD"]
    if not re.fullmatch(r"[a-zA-Z_][a-zA-Z0-9_-]{0,30}[$]?", username):
        raise ValueError()
    if not password or any(char in password for char in ("\n", "\r", "\0")):
        raise ValueError()
except (OSError, ValueError, KeyError):
    sys.exit("Invalid firstboot credentials")
print(username)
print(password)
PYCODE
    )
    [ "${#credentials[@]}" -eq 2 ] || exit 1
    USERNAME=${credentials[0]}
    PASSWORD=${credentials[1]}
	# Create user
	useradd -m -s /bin/bash -G wheel -- "${USERNAME}"
	chpasswd <<<"${USERNAME}:${PASSWORD}"
	# Disable initial-setup
	systemctl disable initial-setup
	rm -f /etc/reconfigSys
	# Rewmove firstboot setup file
	rm /boot/switchroot/firstboot
fi

systemctl disable l4t-firstboot
