#!/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.

console=
if ! [ -f /var/run/console-device ]; then
	# Get the configure consoles using sysctl
	#   's#^.*: ##'   : remove the prompt
	#   's#/.*$##'    : remove unconfigured devices
	#   's#dcons,##g' : remove dcons
	#   's#,# #g'     : separate consoles with spaces instead of commas
	consoles=$(sysctl "kern.console" | sed -e 's#^.*: ##' \
	                                       -e 's#/.*$##' \
					       -e 's#dcons,##g' \
					       -e 's#,# #g')

	for c in $consoles ; do
		case $c in
			# Serial devices
			ttyu*|cuau*)
				console="$c"
				break
				;;
			# Virtual consoles
			ttyv*)
				console=$c
				break
				;;
			consolectl*)
				console="ttyv0"
				break
				;;
			# Unknown consoles, ignore them
			*)
				;;
		esac
	done

	if [ -z "$console" ]; then
		# Still nothing? Default to /dev/console.
		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) "$@"
