#!/bin/sh

# In order to give proper access to the tty, we need to locate the device
# corresponding to the console we are actually using.

if ! [ -f /var/run/console-device ]; then
	# If the kernel emitted an "handover" message, then it's the one
	console="$(dmesg -s 65535 |
		sed -n -e 's/.*\] console handover: boot \[.*\] -> real \[\(.*\)\]$/\1/p')"

	if [ -z "$console" ]; then
		# Retrieve all enabled consoles from boot log
		consoles="$(dmesg -s 65535 |
			sed -n -e 's/.*\] console \[\(.*\)\] enabled/\1/p')"
		# Only one console? Then we are good.
		if [ $(echo "$consoles" | wc -l) -eq 1 ]; then
			console="$consoles"
		fi
	fi

	if [ -z "$console" ]; then
		# Locate the last enabled console present on the command line
		for arg in $(cat /proc/cmdline); do
			case $arg in
			    console=*)
				arg=${arg#console=}
				if echo "$consoles" | grep -q "^${arg%%,*}$"; then
					console=${arg%%,*}
				fi
				;;
			esac
		done
	fi

	if [ -z "$console" ]; then
		# Still nothing? Default to /dev/console for safety
		console=console
	fi
	echo /dev/$console > /var/run/console-device
fi

# Some other session may have it as ctty. Steal it from them
exec /sbin/steal-ctty $(cat /var/run/console-device) "$@"
