#!/bin/sh

DIR=/tmp
FILES=eeprom

# check/select pma table
EF=$DIR/$FILES
PF=/ross/etc/pma_rev.txt

select_pma() {
        echo -n "Selecting PMA tuning values"
        # if the the pma file exists, leave it as is, otherwise
        if [ ! -f "$PF" ]; then
                # if the frame has a PMA default in eeprom,
                # write that to the pma_rev.txt config file
                # otherwise let the frame handle it.    
                grep "PMA_REV" "$EF"
                if [ $? = 0 ]; then
                        grep "PMA_REV" "$EF" > "$PF"
                        echo "PMA: Using default table from $EF:"
                        cat "$PF"
                else
                        echo "PMA: No default PMA table found in $EF"
                fi
        else
                echo "Selected PMA table is:"
                cat "$PF"
        fi
        echo "OK"
}

detect_dev() {
	for DEV in /sys/bus/i2c/devices/1-0050/eeprom \
		   /sys/bus/i2c/devices/0-0050/eeprom
	do
		if dd if=$DEV bs=1 count=1 >/dev/null 2>/dev/null
		then
			return
		fi
	done

	echo "$0: cannot access EEPROM"
	exit 1
}

pack() {
	set -o pipefail
	tar -C $DIR -zc $FILES | dd of=$DEV bs=1k seek=$1 2>/dev/null
}

unpack() {
	set -o pipefail
	dd if=$DEV bs=1k count=1 skip=$1 2>/dev/null |
		gunzip -c | tar x -C $DIR $FILES
}

ask() {
	test -e $DIR/$FILES && . $DIR/$FILES
	> $DIR/$FILES-
	for var in $* ; do
		eval old=\$$var
		local val=
		until expr "$val" : "[^']\+$" >/dev/null ; do
			read -p "$var=$old ? " val
			val=${val:-$old}
		done
		echo "$var='$val'" >> $DIR/$FILES-
	done
	mv $DIR/$FILES- $DIR/$FILES
}

case "$1" in
    start)
	detect_dev
	unpack 0 || unpack 1 || $0 ask
	select_pma
	;;
    save)
	detect_dev
	pack 0 && pack 1
	;;
    ask)
	ask ASSEMBLY SERIAL MAC0 MAC1 PRODUCT PMA_REV
	echo "Writing..."
	$0 save
	echo "Done."
	;;
    *)
	echo "Usage: $0 {start|save|ask}"
	exit 1
esac

exit $?

# The following functions are not used, but are kept for
# possible future usage.  They are used to compare the
# embedded timestamp within two Gzip files.

gziptime() {
	# Extract timestamp from (assumed) gzip file header
	# 4 bytes at offset 4, little-endian byte order
	hexdump -C -n4 -s4 -v $1 | awk '{ print $5 $4 $3 $2 }'
}

comparetime() {
	# Compares timestamps within two gzip files
	# Returns 1 if file1 is newer, otherwise returns 0.
	TIME1=`gziptime $1`
	TIME2=`gziptime $2`
	expr 0x$TIME1 \> 0x$TIME2
}
