#!/bin/sh
set -e

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

write_console() {
	if ! grep -q "$1" "$2"; then
		if ! grep -q "# serial console added by debian-installer" "$2"; then
			echo "" >> "$2"
			echo "# serial console added by debian-installer" >> "$2"
		fi
		echo "$1" >> "$2"
	fi
}		

# 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/}

# Testing for hvc and hvsi here may be useless as they would normally be
# redirected to /dev/console, which is covered by the code section below.
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

	write_console "$rawconsole" /target/etc/securetty
	if [ -n "$console" ] && [ "$console" != "$rawconsole" ]; then
		write_console "$console" /target/etc/securetty
	fi
	;;
esac

# Set up virtualized console via onboard service processor (hvsi/hvc)
DT_ROOT=/proc/device-tree
if [ -e $DT_ROOT/chosen/linux,stdout-path ]; then
	chosen_dev=$(cat $DT_ROOT/chosen/linux,stdout-path)
	case $chosen_dev in
	    /vdevice/vty@30000000)
		case $(cat ${DT_ROOT}${chosen_dev}/compatible) in
		    hvterm-protocol)
			console=hvsi0 ;;
		    hvterm|hvterm1)
			console=hvc0 ;;
		    *)
			log "Unable to determine type of virtualized console"
			exit 1
			;;
		esac
		;;
	    /vdevice/vty@30000001)
		console=hvsi1 ;;
	    /spider/serial)
		console=hvc0 ;;
	    *)
		exit 0 ;;
	esac

	log "Setting up virtualized serial console on /dev/$console"
	if [ -f /target/etc/inittab ]; then
		# Disable regular VTs
		sed -i -e "s/^\([1-6]\):/#\1:/" /target/etc/inittab

		console_line="co:2345:respawn:/sbin/getty $console 9600 vt100"
		if grep -q "^#\?co:" /target/etc/inittab; then
			sed -i -e "s|^#\?co:.*$|$console_line|" \
				/target/etc/inittab
		else
			sedexp="/^#1:/i\\$console_line\\"
			sed -i -e "$sedexp" /target/etc/inittab
		fi
	fi
	if [ -f /target/etc/event.d/tty1 ]; then
		sed -e "s/^\(exec.*getty \).*/\1-L $console 9600 vt100/" \
		    -e "s/tty1/$console/g" \
		    /target/etc/event.d/tty1 > /target/etc/event.d/$console
	fi
fi
