#!/bin/bash
# emulate: /sbin/agetty -L $speed console for console != vga/framebuffer console

#echo "$0: called with '$*'" > /dev/kmsg

stop_me () {
	kill -STOP $$
	exit 1
}

kernel_console=
getty_options=
getty_device=
getty_speed=
getty_TERM=

until [ "$#" = "0" ] ; do
	case "$1" in
		-i|-h|-L|-m|-n|-w)
			getty_options="$getty_options $1"
			shift
		;;
		-*)
			getty_options="$getty_options $1 $2"
			shift 2
		;;
		*)
			case "$1" in
				[0-9]*)
				getty_speed=$1
				getty_device=$2
				;;
				*)
				getty_speed=$2
				getty_device=$1
				;;
			esac
			getty_TERM=$3
			break
		;;
	esac
done

getty_speed=`stty speed < /dev/$getty_device`

if test -z "$getty_speed"
then
	echo "${0}: can not determine '$getty_device' speed" > /dev/kmsg
	stop_me
	exit 1
fi

guess_powerpc_autoconsole() {
	local prop
	if test -f /proc/device-tree/chosen/linux,stdout-path
	then
		prop=`cat /proc/device-tree/chosen/linux,stdout-path`
		prop="${prop##*/}"
		case "$prop" in
			display@*) echo tty1 ;;
			serial@3f8) echo ttyS0 ;; # maple
			serial@i3f8) echo ttyS0 ;;
			serial@i2f8) echo ttyS1 ;;
			serial@i898) echo ttyS2 ;;
			serial@i890) echo ttyS3 ;;
			vty@0) echo hvc0 ;;
			vty@30000000) echo hvsi0 ;;
			vty@30000001) echo hvsi1 ;;
			# some Exar and Jasmine PCI cards have serial@[0123]
			# but since its pci, the ttyS# number cant be guessed
			serial@0) echo ttyS0 ;;
			*) echo "$0: unhandled stdout '$prop'" > /dev/kmsg ;;
		esac
	fi
}

if test "$getty_device" = "console"
then
	read kernel_cmdline < /proc/cmdline
	for i in $kernel_cmdline ''
	do
		case "$i" in
			console=*)
			kernel_console="${i#*=}"
			kernel_console="${kernel_console%%,*}"
			;;
		esac
	done
	if test -z "$kernel_console"
	then
		# check SuSE TIOCGDEV, remove /dev/
		kernel_console="`showconsole < /dev/console`"
		kernel_console="${kernel_console##*/}"
	fi
	if test -z "$kernel_console"
	then
		kernel_console="`guess_powerpc_autoconsole`"
	fi
	case "$kernel_console" in
		tty[0-9]*)
		stop_me
		exit 1
		;;
	esac
fi

exec /sbin/agetty $getty_options $getty_speed $getty_device $getty_TERM
