#!/bin/sh

. /lib/live/config.sh

## live-config(7) - System Configuration Components
## Copyright (C) 2026 Aitor <aitor@genuen.org>
## Copyright (C) 2006-2015 Daniel Baumann <mail@daniel-baumann.ch>
##
## This program comes with ABSOLUTELY NO WARRANTY; for details see COPYING.
## This is free software, and you are welcome to redistribute it
## under certain conditions; see COPYING for details.


#set -e

Cmdline ()
{
	# Reading kernel command line
	for _PARAMETER in ${LIVE_CONFIG_CMDLINE}
	do
		case "${_PARAMETER}" in
			live-config.noautologin|noautologin)
				LIVE_CONFIG_NOAUTOLOGIN="true"
				;;

			live-config.nottyautologin|nottyautologin)
				LIVE_CONFIG_NOTTYAUTOLOGIN="true"
				;;

			live-config.username=*|username=*)
				LIVE_USERNAME="${_PARAMETER#*username=}"
				;;
		esac
	done
}

Init ()
{
	# Disables both console and graphical autologin.
	case "${LIVE_CONFIG_NOAUTOLOGIN}" in
		true)
			exit 0
			;;
	esac

	# Disables console autologin, no matter what mechanism
	case "${LIVE_CONFIG_NOTTYAUTOLOGIN}" in
		true)
			exit 0
			;;
	esac

	# Checking if package is installed or already configured
	# (DM hooks touch this state file to skip console agetty -a, like xinit.)
	if [ ! -e /etc/s6-rc/config/tty1.conf ] || \
	   component_was_executed "s6"
	then
		exit 0
	fi

	echo -n " s6"
}

Config ()
{
	# Configure agetty autologin via s6-rc tty*.conf ARGS
	if [ -n "${LIVE_USERNAME}" ]
	then
		for _conf in /etc/s6-rc/config/tty[1-6].conf
		do
			[ -f "${_conf}" ] || continue
			if grep -qE '^ARGS=.*-a ' "${_conf}"; then
				continue
			fi
			if grep -q '^ARGS=' "${_conf}"; then
				sed -i -e "s|^ARGS=\"|ARGS=\"-a ${LIVE_USERNAME} |" "${_conf}"
			else
				_tty="$(basename "${_conf}" .conf)"
				echo "ARGS=\"-a ${LIVE_USERNAME} -L -8 ${_tty} 115200\"" >> "${_conf}"
			fi
		done
	fi

	# Creating state file
	touch /var/lib/live/config/s6
}


Cmdline
Init
Config
