#!/bin/bash

# setconsole
#
# Written by Erik Troan <ewt@redhat.com>

console=""
condev=""

usage () {
    echo "usage: $0 [--speed foo] <video|serial|ttya|ttyb|cua0|cua1|ttyS0|ttyS1>" >&2
    exit 1
}

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
    condev=$2
}

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

	video|serial)
	    setconsole $1 $1
	    ;;

	ttya|cua0|ttyS0)
	    setconsole ttya cua0
	    ;;

	ttyb|cua1|ttyS1)
	    setconsole ttyb cua1
	    ;;

	*)
	    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
	condev=cua0
    else
	console=ttyb
	condev=cua1
    fi
}

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

[ $console != video ] && {
    if ! grep -s "^[0-9].*getty.*${condev} > /dev/null" < /etc/inittab ; then
	# need to add a getty entry for this device
	line=`grep -n '^[0-9]' /etc/inittab | tail -1 | cut -d: -f1`
	sed "${line}s|.*|&"'\
'"1:12345:respawn:/sbin/getty $condev $speed vt100|" < /etc/inittab > /root/.inittab.$$
	mv /root/.inittab.$$ /etc/inittab
    fi

    # remove other ttys from inittab
    sed "s/^[0-9].*tty[0-9]/#&/" < /etc/inittab > /root/.inittab.$$
    mv /root/.inittab.$$ /etc/inittab

    # make sure this is in /etc/securetty: FIXME: should this get undone??
    if ! grep -s $condev /etc/securetty > /dev/null; then
	echo $condev >> /etc/securetty
    fi

    ttydev=$condev
}

[ $console = video ] && {
    # restore normal ttys and remove serial ttys
    sed "/^#[0-9].*tty[0-9]/s/^#//" < /etc/inittab |
	sed "/^[0-9].*getty.*cua.*/d" > /root/.inittab.$$
    mv /root/.inittab.$$ /etc/inittab

    ttydev=tty0
}

rm -f /dev/systty /dev/console
ln -s $ttydev /dev/systty
ln -s $ttydev /dev/console
