#!/bin/sh

## live-config(7) - System Configuration Components
## Copyright (C) 2026 HuohuoPlaysOpenBSD <1652738367@qq.com>
##
## 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 ()
{
	case "${LIVE_CONFIG_NOAUTOLOGIN}" in
		true)
			exit 0
			;;
	esac

	case "${LIVE_CONFIG_NOTTYAUTOLOGIN}" in
		true)
			exit 0
			;;
	esac

	if [ ! -e /var/lib/dpkg/info/openrc.list ] || \
	   [ -e /var/lib/live/config/openrc ]
	then
		exit 0
	fi

	echo -n " openrc"
}

Config ()
{
	if [ -n "${LIVE_USERNAME}" ]
	then
		for _TTY in 1 2 3 4 5 6
		do
			_AGETTY_CONF="/etc/conf.d/agetty.tty${_TTY}"

			if [ ! -e "/etc/init.d/agetty.tty${_TTY}" ]
			then
				if [ -e "/etc/init.d/agetty" ]
				then
					ln -sf /etc/init.d/agetty "/etc/init.d/agetty.tty${_TTY}"
				else
					continue
				fi
			fi

			if [ -e "${_AGETTY_CONF}" ]
			then
				sed -i '/^agetty_options=/d' "${_AGETTY_CONF}"
			fi
			
			cat >> "${_AGETTY_CONF}" << EOF
agetty_options="--autologin ${LIVE_USERNAME} --noclear"
EOF

			if command -v rc-update >/dev/null 2>&1
			then
				rc-update add "agetty.tty${_TTY}" default >/dev/null 2>&1 || true
			fi
		done
	fi

	echo -n " tty-autologin"
	touch /var/lib/live/config/openrc
}

Cmdline
Init
Config
