#!/bin/bash
#
# LX2162 SoM SPD EEPROM Patch
# for revision 1.1 with 8GB DDR
#
# Copyright 2024 Josua Mayer <josua@solid-run.com>
#

# we don't have status code checks for each step - use "-e" with a trap instead
function error() {
	status=$?
	printf "ERROR: Line %i failed with status %i: %s\n" $BASH_LINENO $status "$BASH_COMMAND" >&2
	exit $status
}
trap error ERR
set -e

instance=0
if [ ! -e /sys/bus/i2c/devices/0-0051/eeprom ]; then
	#echo spd 0x51 > /sys/bus/i2c/devices/i2c-0/new_device # "spd" read-only
	echo 24c02 0x51 > /sys/bus/i2c/devices/i2c-0/new_device
	instance=1
fi

s=0
echo -n -e \
'\x02\x11\x0c\x03\x85\x21\x00\x08\x00\x60\x00\x03\x01\x0b\x00\x00'\
'\x00\x00\x05\x0a\xf8\xff\x02\x00\x6e\x6e\x6e\x11\x00\x6e\xf0\x0a'\
'\x20\x08\x00\x05\x00\xa8\x1b\x28\x28\x00\x78\x00\x14\x3c\x00\x00'\
'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x16\x22\x0e\x30'\
'\x14\x36\x11\x2f\x03\x22\x10\x30\x0e\x34\x14\x36\x10\x2b\x00\x00'\
'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'\
'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'\
'\x00\x00\x00\x00\x00\x00\x9c\xb4\x00\x00\x00\x00\x00\x00\xc3\x4f'\
'\x0f\x11\x20\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'\
'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'\
'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'\
'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'\
'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'\
'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'\
'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'\
'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xef\x55'\
> /sys/bus/i2c/devices/0-0051/eeprom || s=$?
if [ $s -ne 0 ]; then
	echo "Failed to write EEPROM!"
fi

s=0
echo 058fda824c83c183de262c5eb0dee13a /sys/bus/i2c/devices/0-0051/eeprom | md5sum -c || s=$?

if [ $instance -ne 0 ]; then
	echo 0x51 > /sys/bus/i2c/devices/i2c-0/delete_device
fi

exit $s
