#!/bin/sh
set -e

log() {
	logger -t finish-install "$@"
}

# 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 init 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
	if [ -f /target/etc/inittab ]; then
		sed -i -e "s/^\([1-6]\):/#\1:/" \
		    -e "s/^#T0\(.*ttyS\).*/T$ttyline\1$ttyline $ttyspeed $ttyterm/" \
		    /target/etc/inittab
	fi
	if [ -f /target/etc/event.d/tty1 ]; then
		sed -e "s/^\(respawn.*getty \).*/\1-L ttyS$ttyline $ttyspeed $ttyterm/" \
		    -e "s/tty1/ttyS$ttyline/g" \
		    /target/etc/event.d/tty1 > /target/etc/event.d/ttyS$ttyline
	fi
	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
