#!/bin/bash
#
# Copyright (c) Authors: https://www.armbian.com/authors
#
# This file is licensed under the terms of the GNU General Public
# License version 2.0. This program is licensed "as is" without any
# warranty of any kind, whether express or implied.

# Console autologin helper for serial-getty@.service.
#
# USB gadget serial ports have no reader until a host opens the ACM device;
# wait for CR before autologin emits anything, so first-login output is not
# buffered and replayed as garbage on the first connection. A complete preset
# has nobody at the console and must stay unattended.

port=${1:?"missing tty"}
term=${2:-linux}
marker=/root/.not_logged_in_yet
preset_cache=/run/armbian-firstlogin-preset.conf

. /usr/lib/armbian/armbian-common

set -- --noissue --autologin root "$port" "$term"

case "$port" in
ttyGS*)
	# Resolve a remote preset before deciding whether input is required. Reuse
	# its cache here and in firstlogin; a download or validation failure keeps
	# the wait, while firstlogin retains the original failure handling.
	# shellcheck disable=SC1090
	if armbian_firstlogin_prepare_preset; then
		# shellcheck disable=SC1090
		. "$marker" 2>/dev/null
		[[ -n "${PRESET_CONFIGURATION}" && -f "${preset_cache}" ]] && marker=${preset_cache}
		# A partial preset still needs a terminal for the missing credentials.
		# Source and test separately: a marker's last command may exit nonzero.
		if ! (. "$marker" 2>/dev/null; armbian_firstlogin_preset_unattended); then
			set -- -w "$@"
		fi
	else
		set -- -w "$@"
	fi
	;;
esac

exec /sbin/agetty "$@"
