#!/bin/sh
set -e

log() {
	logger -t prebaseconfig "$@"
}

# Since this script is running with debconf, 'tty' does
# not give reliable answers about what sort of terminal
# we have.  The stdin of /sbin/debian-installer seems
# to tell the truth.
inst_pid=$(pidof debian-installer | cut -d" " -f1)
rawconsole=$(readlink /proc/${inst_pid}/fd/0)
console=$(mapdevfs "$rawconsole") 
rawconsole=${rawconsole#/dev/}
console=${console#/dev/}

case "$console" in
ttyS*)
	log "Configuring /etc/inittab for serial console"
	ttyspeed=$(chroot /target stty --file /dev/$console speed)
	ttyline=${console#ttyS}
	ttyterm="$TERM"

	if [ -z "$ttyterm" ]; then ttyterm=vt100; fi
	if [ -z "$ttyspeed" ]; then ttyspeed=9600; fi
	sed -i -e "s/^\([1-6]\):/#\1:/" \
	    -e "s/^#T0\(.*ttyS\).*/T$ttyline\1$ttyline $ttyspeed $ttyterm/" \
	    /target/etc/inittab
	echo "# serial console added by debian-installer" >> /target/etc/securetty
	echo "$rawconsole" >> /target/etc/securetty
	if [ -n "$console" ] && [ "$console" != "$rawconsole" ]; then
		echo "$console" >> /target/etc/securetty
	fi
;;
esac
