#! /bin/sh

ITAB=/etc/inittab

set -e

case "$1" in
  start)
	console=''
	if /usr/sbin/chroot /mnt/initfs cal-tool --get-rd-flags | grep -q serial-console; then
	    console='Yes'
	fi

        changed=''
	if [ -c /dev/ttyUSB0 ] && [ "$console" == "Yes" ]; then
		if grep -q '^#T1.*ttyUSB0.*' $ITAB ; then
			sed -ie 's/^#\(T1.*ttyUSB0.*\)/\1/' $ITAB
			changed='Yes'
		fi
	else
		if grep -q '^T1.*ttyUSB0.*' $ITAB ; then
			sed -ie 's/^\(T1.*ttyUSB0.*\)/#\1/' $ITAB
			changed='Yes'
		fi
	fi
	
	#test if we can read ttyS1, we have serial console there device on ttyS0
	if [ -c /dev/ttyS1 ] && [ "$console" == "Yes" ] && dd of=/dev/ttyS1 count=1 bs=1 if=/dev/zero ; then
		if grep -q '^#T2.*ttyS1.*' $ITAB ; then 
			sed -ie 's/^#\(T2.*ttyS1.*\)/\1/' $ITAB
			changed='Yes'
		fi
		if grep -q '^T0.*ttyS0.*' $ITAB ; then 
		    sed -ie 's/^\(T0.*ttyS0.*\)/#\1/' $ITAB
		    changed='Yes'
		fi
	else
		if grep -q '^T2.*ttyS1.*' $ITAB ; then 
			sed -ie 's/^\(T2.*ttyS1.*\)/#\1/' $ITAB
			changed='Yes'
		fi
		#and check serial console on ttyS0

		if [ -c /dev/ttyS0 ] && [ "$console" == "Yes" ] && dd of=/dev/ttyS0 count=1 bs=1 if=/dev/zero ; then
		    if grep -q '^#T0.*ttyS0.*' $ITAB ; then 
			sed -ie 's/^#\(T0.*ttyS0.*\)/\1/' $ITAB
			changed='Yes'
		    fi
		else
		    if grep -q '^T0.*ttyS0.*' $ITAB ; then 
			sed -ie 's/^\(T0.*ttyS0.*\)/#\1/' $ITAB
			changed='Yes'
		    fi
		fi
	fi

	MODE=`/usr/sbin/chroot /mnt/initfs cal-tool --get-rd-mode`
	if [ x$MODE = xenabled ]; then
		if grep -q '^root:!SU.odxvRwp3Vs' /etc/passwd; then
			/usr/sbin/usermod -U root
		fi
	else
		if grep -q '^root:SU.odxvRwp3Vs' /etc/passwd; then
			/usr/sbin/usermod -L root
		fi
	fi

	[ "$changed" = "Yes" ] && telinit Q 
	;;
  stop|reload|restart|force-reload)
	;;
  *)
	echo "Usage: $0 start" >&2
	exit 1
	;;
esac

exit 0
