#!/bin/sh

#set -e

# initramfs-tools header

PREREQ=""

prereqs()
{
        echo "${PREREQ}"
}

case "${1}" in
        prereqs)
                prereqs
                exit 0
                ;;
esac

# live-initramfs header

DESCRIPTION="Setting up serial console for inittab ..."

. /scripts/live-functions

log_begin_msg "$DESCRIPTION"

# live-initramfs script

# Arrange for shells on virtual consoles, rather than login prompts

for x in $(cat /proc/cmdline); do
  	case $x in 
 		live-getty)
 			export LIVE_GETTY=1 
 			;;
 		console=*)
			export DEFCONSOLE=$(sed -e 's%.*console=%console=%' /proc/cmdline)
			;;
		autoinstall=*)
			AUTOINSTALL=$(sed -e 's%.*autoinstall=%%' /proc/cmdline | \
						  cut -d " " -f 1 )
			;;
  	esac	
done
    		
_log_msg "DEFCONSOLE=${DEFCONSOLE}"
_log_msg "LIVE_GETTY=${LIVE_GETTY}"
_log_msg "AUTOINSTALL=${AUTOINSTALL}"

if [ ! -z "${DEFCONSOLE}" ]; then
   if echo "${DEFCONSOLE}" | grep -qs ttyS; then
        # AUTOMATIC SERIAL CONSOLE #
        PORT=$(echo "${DEFCONSOLE}" | \
            sed -e 's%^console=ttyS%%' -e 's%,.*%%')
        SPEED=$(echo "${DEFCONSOLE}" | \
            sed -e 's%^console=ttyS[0-9]\+,%%' \
                -e's%\([0-9]\+\).*%\1%')

		cmd1="/^T0:/ s/${PORT} 9600/${PORT} ${SPEED}/"
		
		_log_msg "Setting Serial Port to ttyS${PORT} ${SPEED}"
		
		sed -i -e "${cmd1}" /root/etc/inittab 
    fi
fi

if [ ! -z "${AUTOINSTALL}" ] ; then
	echo "V0:23:once:/usr/local/sbin/autoinstall.sh ${AUTOINSTALL}" >> /root/etc/inittab
	sed -i -e "s/^T0/#T0/" /root/etc/inittab 
fi

log_end_msg

exit 0
