#!/bin/bash
# This script is intended to be executed from the nios2_command_shell

FILE_SOF="../config.sof"
FILE_ELF="../software/config_de0/config_de0.elf"
FLASH_SOF="config_epcs.flash"
FLASH_ELF="config_epcs_elf.flash"
EPCS_BASE="0x21800"

# if flash file does not exist, or if it is older than the sof file
if [ ! -f $FLASH_SOF ] || [ $FLASH_SOF -ot $FILE_SOF ]; then 
	# transform the sof into flash
	sof2flash --input=$FILE_SOF --output=$FLASH_SOF --epcs
	if [ $? -ne 0 ]; then
		exit -1
	fi
fi
# if flash file does not exist or if sources are more recent
if [ ! -f $FLASH_ALL ] || [ $FLASH_ELF -ot $FILE_ELF ] || [ $FLASH_ELF -ot $FLASH_SOF ]; then
	# add the program after the configuration file
	elf2flash --input=$FILE_ELF --output=$FLASH_ELF --epcs --after=$FLASH_SOF
	if [ $? -ne 0 ]; then
		exit -1
	fi
fi
# configure the FPGA
nios2-configure-sof $FILE_SOF
if [ $? -ne 0 ]; then
	exit -1
fi
# Program the EPCS
nios2-flash-programmer $FLASH_SOF --base=$EPCS_BASE --epcs --program
if [ $? -ne 0 ]; then
	echo
	echo "It seems that the EPCS could not be programmed."
	echo "Try to copy the file 'nios2-flash-override.txt' into your 'nios2eds/bin' directory"
	exit -1
fi
nios2-flash-programmer $FLASH_ELF --base=$EPCS_BASE --epcs --program
if [ $? -ne 0 ]; then
	exit -1
fi

echo "Your board should be now configured, try to reinitialize it."
