#! /bin/sh

if [ $# -ne 1 ]; then
	echo "Usage: $0 <serial-number>"
	exit 1
fi

serial=$1
invalid_chars=`echo -n "$serial" | sed 's/[0-9A-F]*//g'`

if [ -n "$invalid_chars" ]; then
	echo The serial number must only contain the characters 0-9 and A-F
	exit 1
fi

if [ `echo -n $serial | wc -c` -lt 12 ]; then
	echo The serial number must be at least 12 characters
	exit 1
fi

echo Writing serial number '$serial' to the flash user area...
tmpfile=`mktemp rips-serial.XXXXXXXXXX`
printf '%s\0' $serial > $tmpfile
avr32program program -vefinternal@0x80000000 -Fbin -O0x80800000 $tmpfile
retcode=$?
rm $tmpfile

if [ $retcode -eq 0 ]; then
	echo The serial number was written successfully
else
	echo Failed to write the serial number to flash user area
fi

exit $retcode
