#!/bin/bash
#------------------------------------------------------------------------------
#
#	\brief	flash file to openocd device
#
#		The openocd server has to be running.\n
#		The size to be erased is calculated automatically.
#
#		If no parameter is given a "gdb monitor help" is executed to
#		give information whate remote gdb commands can be used.
#
#		Local gdb (not the one of the toolchain) seems to work 
#		correctly.
#
#	\date	20121121
#	\author	Maximilian Seesslen <development@seesslen.net>
#
#------------------------------------------------------------------------------


set -e
set -u


export PATH="$PATH:/opt/tcb/armv5tel-unknown-linux-gnueabi/sysroot/tools/bin"
export CARCH="armv5tel-unknown-linux-gnueabi-gdb"

# GDB="armv5tel-unknown-linux-gnueabi-gdb"
GDB="gdb"

if [ "$#" -gt "0" ]; then
    file="$PWD/$1"

    filesize=$(stat -c "%s" "$file")
    if [ "$filesize" -gt "524288" ]; then
	echo "File seems to be too big, i break up... : $filesize"
        exit 22
    fi
    blocksize=64
    let blocks="(($filesize)/($blocksize*1024))+1"

    echo "Blocks: $blocks"

else
    file=""
fi


# one sector is 16K, 64K, 128K?
echo "Flashing file \"$file\""


if [ ! -z "$file" ]; then
     $GDB \
	--eval-command="set arm abi AAPCS" \
        --eval-command="target remote localhost:3333" \
	--eval-command="monitor reset halt" \
	--eval-command="monitor flash erase_address pad 0x08000000 $filesize" \
	--eval-command="monitor flash write_bank 0 $file 0" \
	--eval-command="monitor reset halt" \
        --eval-command="monitor reset run" \
	--eval-command="detach" \
        --eval-command="quit" \

else
    $GDB \
	--eval-command="set arm abi AAPCS" \
        --eval-command="target remote localhost:3333" \
	--eval-command="monitor reset halt" \
	--eval-command="monitor flash probe 0" \
	--eval-command="monitor flash help" \

fi

#        --eval-command="monitor flash probe 0" \
#        --eval-command="monitor flash erase_address pad 0x08000000 $filesize" \
#	--eval-command="monitor flash write_bank 0 $file 0" \
# 	--eval-command="monitor program $file" \


#---fin------------------------------------------------------------------------
