#!/bin/sh

OBJCOPY=m68k-eyebot-elf-objcopy
SREC2BIN=srec2bin

# Check that a filename was specified.
if test -z "$1"
then
    echo "Usage:"
    echo "`basename $0` <filename> download .hx, .hex, .elf programs or data to EyeBot"
    echo "`basename $0` -u <filename> upload data from EyeBot"
    exit 1
fi

if test ! "$1" = "-u"; then #download
    # Check that the file exists.
    if ! test -e "$1"
    then
	echo "The file \"$1\" does not exist."
	exit 1
    fi

    # Check that the file can be read.
    if ! test -r "$1"
    then
	echo "The file \"$1\" cannot be read."
	exit 1
    fi

    if [[ "$1" == *.elf ]]; then
        TMPFILE=`mktemp`
	HEXFILE=$TMPFILE
	"$OBJCOPY" -O srec --gap-fill=0 "$1" $HEXFILE
	"$SREC2BIN" -i $HEXFILE "${1%.elf}.hex" >/dev/null
    else
        HEXFILE="$1"
    fi
    
    # Ensure that the file is in the cache before beginning.
    cat "$HEXFILE" > /dev/null

    # Perform the file transfer.
    stty -F /dev/ttyS0 "0:0:80001cb1:8a38:3:1c:7f:15:4:0:1:0:11:13:1a:0:12:f:17:16:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0"
    echo "Downloading \"$HEXFILE\" on COM1 at 57600 bps."
    cat "$HEXFILE" > /dev/ttyS0
else # upload
    # Check that a filename was specified.
    if test -z "$2"
    then
	echo "No filename specified!"
	exit 1
    fi

    # Perform the file transfer.
    stty -F /dev/ttyS0 "0:0:80001cb1:8a38:3:1c:7f:15:4:0:1:0:11:13:1a:0:12:f:17:16:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0"
    echo "Uploading \"$2\" on COM1 at 57600 bps."
    echo "Press Ctrl+C to end the transfer."
    cat /dev/ttyS0 > $2
fi

