#!/bin/sh

source ${CONF_DIR}/config
source ${CONF_DIR}/helpers/functions

EEPROM="/sys/bus/spi/devices/spi0.0/eeprom";
VAR=$1;
ERR=0;
VAL="";
# Check if this script has already been called
# If so we assume config has not changed
if [ ! -r ${EEPROM} ]; then
	# Load all necessary modules, if they have already been loaded modprobe will skip them
	load_module at25;
	if [ "X$?" != "X0" ]; then ERR=1; fi
	load_module dwapbssi;
	if [ "X$?" != "X0" ]; then ERR=2; fi
	if [ "X${ERR}" != "X0" ]; then
		exit ${ERR};
	fi
	usleep 500;
	if [ ! -r ${eeprom} ]; then
		exit 3;
	fi
fi

# if /tmp exist, assume we are fully booted and use it
# otherwise we are in the initrd so put it in / since tmp
# doesn't exist
if [ -e /tmp ]
then
	SPIDATA=/tmp/.spidata
else
	SPIDATA=/.spidata
fi

if [ ! -e ${SPIDATA} ]
then
	cat ${EEPROM} > ${SPIDATA}
	CFGVER=$(grep '^CFG' ${SPIDATA} | sed -e 's|^CFG\([0-9]*\).*|\1|');
	if [ $((CFGVER)) -eq 0 ]
	then
		exit 4;
	fi
fi
VAL=$(grep "${VAR}=" ${SPIDATA} | tail -1 | sed -e "s|.*${VAR}=\([^ ]*\).*|\1|");
echo ${VAL};
exit ${ERR};
