#!/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 | sed "s/ /\n/g" | sort -n | head -n 1)
rawconsole=$(readlink /proc/${inst_pid}/fd/0)
console=$(mapdevfs "$rawconsole") 
rawconsole=${rawconsole#/dev/}
console=${console#/dev/}

case "$console" in
    tty[A-Z]*|hvc*|hvsi*)
	log "Configuring init for serial console"
	consoletype=${console%%[0-9]*}
	ttyline=${console#$consoletype}
	ttyspeed=$(chroot /target stty --file /dev/$console speed)
	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$console $ttyspeed $ttyterm/" \
		    /target/etc/inittab
	fi
	if [ -f /target/etc/event.d/tty1 ]; then
		sed -e "s/^\(exec.*getty \).*/\1-L $console $ttyspeed $ttyterm/" \
		    -e "s/tty1/$console/g" \
		    /target/etc/event.d/tty1 > /target/etc/event.d/$console
	fi

	echo "" >> /target/etc/securetty
	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
