#! /bin/sh

#
# uart console "login" handler for locked boards (runlevel 3)
#
# this allows to store GoogleCast model key into the device during device manufacture;
# but the serial console is still disabled.
#

LEVEL=`cat /proc/sys/kernel/printk`

function disablePrintk()
{
	echo 2 > /proc/sys/kernel/printk
}

function enablePrintk()
{
	echo $LEVEL > /proc/sys/kernel/printk
}

# if the model key is not yet stored, disable kernel messages going onto the console
# so they don't mix up with our status messages
if ! teeStoreKey -v > /dev/null 2>&1; then
	disablePrintk
	echo "# no key"
else
	# this is normally printed by init when getty is disabled - so pretend this script isn't there
	echo "INIT: no more processes left in this runlevel"
fi

while read; do
	if [ "x$REPLY" = "x!importkey" ]; then
		disablePrintk

		echo "# import key"
		if teeStoreKey -g -e -c; then
			# remove old generated certificates/..
			rm /factory/client.*
			sync

			# NOTE: make sure tee-supplicant has time to save the data before power-off/reboot !!!
			#       (with optee, there is a 1-sec delay; the nsdk restart below does "sleep 2")

			# restart everything to apply new keys
			/etc/init.d/nsdk restart

			echo "# done importing key"
		else
			echo "# error importing key"
		fi
	elif [ "x$REPLY" = "x!opendevice" ]; then
		# Create file with unique id
		factory_tool get_unique_id > /tmp/serial.txt

		if [ $? -eq 1 ]; then
			echo "Could not get serial id!"
			break
		fi

		# Read signature from line
		read -p "Signature: " sigFromLine

		# Put signature to the file
		echo "$sigFromLine" > /tmp/sig.txt

		# Convert signature from base64 to bin
		if ! openssl enc -d -A -base64 -in /tmp/sig.txt -out /tmp/sigBin.txt; then
			echo "Converting signature from base64 failed!"
			break
		fi

		# Verify signature
		if openssl dgst -sha256 -verify /home/root/verified-boot.pem -signature /tmp/sigBin.txt /tmp/serial.txt; then
			# Run level 5
			telinit 5
		fi
	elif [ "x$REPLY" = "x!showuniqueid" ]; then
		echo "Unique id: $(factory_tool get_unique_id)"
	elif [ "x${REPLY:0:4}" = "x!ffs" ]; then
		disablePrintk

		# Delegate to FFS handler, if it exists
		if [ -x "/bin/ffs-locked-device-shell" ]; then
			/bin/ffs-locked-device-shell "$REPLY"
		fi
	fi

	# Always make sure kernel messages are enabled in the end
	enablePrintk
done

