#!/bin/sh

. /opt/gira/share/devicestack/ipmodule-init.d-base

HASH_FILE=/etc/dm8603-eeprom.sha256
RESET_FILE=/opt/userdata/.dm8603-eeprom-reset-reboot

case $1 in
	start)
		if [ ! -e ${HASH_FILE} ]
		then
			msg "Skipping verification of DM8603 EEPROM content. The hash file ${HASH_FILE} is missing."
			exit 1
		fi
		msg "Reading DM8603 EEPROM content for verification..."
		EEPROM_STRING=$(ethtool -e lan2-private | grep 0x0 | cut -d ':' -f 2 | cut -f 3 | tr -d '\n' | sed 's/[ \t]*$//' | sed -e 's/\s\+/\\x/g')
		ACTUAL_HASH=$(echo -n -e "\x${EEPROM_STRING}" | sha256sum | cut -d" " -f1)
		EXPECTED_HASH=$(cat ${HASH_FILE} | head -n 1 | cut -d" " -f1)
		if [ _${ACTUAL_HASH}_ = _${EXPECTED_HASH}_ ]
		then
			msg "DM8603 EEPROM is correct. Nothing to do."
			if [ -e ${RESET_FILE} ]
			then
				rm -f ${RESET_FILE}
			fi
		else
			msg "DM8603 EEPROM content is unexpected. Need to reset."
			if [ ! -e ${RESET_FILE} ]
			then
				msg "The device will REBOOT HEREAFTER!"
				touch ${RESET_FILE}
				sync
				# Whether lan2-private or lan1-public doesn't matter. cpu-port will not work.
				# first delete the eeprom.
				ethtool -E lan2-private magic 0x1049 offset 255 length 1 value 0
				# then program the eeprom with static configration.
				ethtool -E lan2-private magic 0x1049 offset 255 length 1 value 1
				# now reboot to load the eeprom.
				sleep 1
				reboot
			else
				msg "The device already did a reset and reboot. Skipping."
				msg "Please delete the following file to allow a new reset."
				msg "rm -f ${RESET_FILE}"
			fi
		fi
		;;
	stop)
		;;
	*)
		usage "/etc/init.d/S35CheckDM8603eeprom.sh start|stop"
esac

exit 0
