#!/bin/sh
## Finally test the TFTP connexion and flash the default firmwares
## 
##	The TFTP connexion might have been used previously but with 
##	this test we ensure that it correctly work 
##
## Linux devices: 
##		wrs# cat /proc/mtd
##		dev:    size   erasesize  name
##		mtd0: 00800000 00020000 "Kernel"
##		mtd1: 08000000 00020000 "Filesystem"
##		mtd2: 00040000 00020000 "Barebox Environment"
##		mtd3: 14000000 00020000 "Available"
##		mtd4: 00840000 00000420 "spi0.0-AT45DB642x"
##
##
## Authors: 
##	- Benoit Rat (Seven Solutions, www.sevensols.com)
##
## GNU Lesser General Public License Usage
## This file may be used under the terms of the GNU Lesser
## General Public License version 2.1 as published by the Free Software
## Foundation and appearing in the file LICENSE.LGPL included in the
## packaging of this file.  Please review the following information to
## ensure the GNU Lesser General Public License version 2.1 requirements
## will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
#######################################################################################################

printf "======: $0\n"
. 000-functions.sh

bin_dir="/tmp"

ret0=1
ret1=1
ret2=1
ret3=1

printf "Flashing at91bootstrap and barebox on dataflash: \n"
ret=0
checkLoadTFTP at91bootstrap.bin 1 ${bin_dir}
checkLoadTFTP barebox.bin 1 ${bin_dir}
if [ $ret -eq "0" ]; then 
	cat ${bin_dir}/at91bootstrap.bin > /dev/mtd4
	ret0=-$?
	dd bs=33792 seek=1 if=${bin_dir}/barebox.bin of=/dev/mtd4 #33792<=>0x8400<=>32ePages<=>32*(1024+32) => 0x8000 without header
	ret1=-$?
	
	printf "Done\n"
fi


bin_dir="/alpha-pts/firmwares/"

printf "Flashing kernel on nandflash: \n"
if [[ -f ${bin_dir}/zImage ]]; then 
	# Flashing kernel (without erasing barebox env)
	flash_eraseall /dev/mtd0  &> /dev/null
	nandwrite --pad  /dev/mtd0  ${bin_dir}/zImage 
	ret2=-$?
	rm ${bin_dir}/zImage 
	printf "Done\n"
else
	printf "${bin_dir}/zImage not found\n"
fi


printf "Flashing Filesystem on nandflash: \n"
if [ -f ${bin_dir}/wrs-image.jffs2.img ]; then 
	# Flashing whole partiton for FS.
	flash_eraseall /dev/mtd1 &> /dev/null
	nandwrite --pad /dev/mtd1 ${bin_dir}/wrs-image.jffs2.img
	ret3=-$?
	rm ${bin_dir}/wrs-image.jffs2.img
	printf "Done\n"
else
	printf "${bin_dir}/wrs-image.jffs2.img not found\n"
fi


exit_multierr $ret0 $ret1 $ret2 $ret3