#!/bin/bash

# setconsole
#
# Written by Erik Troan <ewt@redhat.com>
#            Jakub Jelinek <jj@ultra.linux.cz>

speed=""
console=""

checkprom () {
    [ $console != video ] && [ ! -d /proc/openprom/options ] && {
	echo "/proc/openprom/options does not exist -- cannot setup console" 2>&1
	exit 1
    }
}

setconsole () {
    if [ -n "${console}" ]; then
	usage
    fi
    console=$1
}

while [ $# -gt 0 ]; do
    case $1 in
	--speed)
	    shift;
	    speed=$1;
	    ;;

	video|serial)
	    setconsole $1
	    ;;

	ttya|cua0|ttyS0)
	    setconsole ttya
	    ;;

	ttyb|cua1|ttyS1)
	    setconsole ttyb
	    ;;

	*)
	    usage
	    ;;
    esac

    shift
done
	
[ -z "${console}" ] && usage

[ $console = serial ] && {
    checkprom

    input=$(cat /proc/openprom/options/input-device | cut -d\' -f2)
    output=$(cat /proc/openprom/options/output-device | cut -d\' -f2)

    if [ $input != $output ]; then
	echo "The PROM input device is not the same as the PROM output device" 2>&1
	exit 1
    fi

    if [ $input = ttya ]; then
	console=ttya
    else
	console=ttyb
    fi
}

[ $console != video -a -z "$speed" ] && {
    checkprom
    speed=$(cat /proc/openprom/options/${console}-mode | cut -d, -f1 | cut -d\' -f2)
}

if grep -s "^1:.*getty.*console.*vt100$" > /dev/null < /etc/inittab.serial ; then
	if ! grep -s "^1:.*getty.*console[ 	]*${speed}[ 	]*vt100\$" > /dev/null < /etc/inittab.serial; then
		sed "s|^\(1:.*getty.*console\)[ 	]*[0-9]*[ 	]*\(vt100\)\$|\1 ${speed} \2|" < /etc/inittab.serial > /root/.inittab.$$
	mv -f /root/.inittab.$$ /etc/inittab.serial
	fi
fi
