#!/bin/sh

# config file is a text representation of the binary values in the prom.
#
# the last two rows are version information (null terminated strings)
#

. /usr/local/bin/sig_catcher

calculate_addr()
#$1 : offset
{
	#Calculate the offset and salve address
	#bit 3, 2, 1 of slave_addr are bit 10, 9, 8 of EEPROM offset
	offset_b10_8=$(($1 & 0x700))
	offset_b7_0=$(($1 & 0xff))
	slave_addr=$(( $EEPROM_SA | ($offset_b10_8>>7) ))
	offset_b7_0=$(echo $offset_b7_0|awk '{printf "%x",$1}')
	slave_addr=$(echo $slave_addr|awk '{printf "%x",$1}')
}
if [ $# -lt 1 ]; then
    echo "Usage: $0 <filename>"
    exit 1
fi

platform=$(cat /var/run/platform)

filename=$1
EEPROM_SA=0xa0
row_index=1 #1 base
total_rows=$(wc -l $filename | awk '{print $1}')
offset=0
offset_b10_8=0
offset_b7_0=0
UNIQUE_FILENAME="/tmp/ddr_i2c_dump$$"
if [ -f $UNIQUE_FILENAME ] ; then
	rm $UNIQUE_FILENAME 
fi
case $platform in
	Lodi|Madera|Livermore)
		# program in config information at offset 0
		while [ $row_index -le $total_rows ]; do

			val=$(head -n $row_index $filename | tail -n 1)

			offset=$((($row_index-1) * 16))
			calculate_addr $offset
			/usr/local/bin/i2c-test -b 5 -s $slave_addr -m 1 -w -d $offset_b7_0 $val > /dev/null
			row_index=$(( $row_index + 1))
		done


		#compare
		row_index=1
		while [ $row_index -le $total_rows ]; do

			offset=$((($row_index-1) * 16))
			calculate_addr $offset
			/usr/local/bin/i2c-test -b 5 -s $slave_addr -m 1 -rc 16 -d $offset_b7_0 |tail -3 |head -1 >> $UNIQUE_FILENAME
			row_index=$(( $row_index + 1))
		done

	;;
	*)
		echo "This feature is not supported in ${platform:-no platform text goes here}"
	;;
esac


diff -bB $UNIQUE_FILENAME $filename
if [ $? -eq 0 ]; then
    echo "Programmed successfully"
else
    echo "Did NOT program correctly! "
fi

rm  $UNIQUE_FILENAME
