#!/bin/sh

SHAREDIR="/usr/share/snek"

BOOT_FILE=$SHAREDIR/bootloader-snekboard.bin
SNEK_FILE=$SHAREDIR/snek-board-1.5.elf

mode=arg

for i in "$@"; do
    case "$mode" in
	arg)
	    case "$i" in
		-elf)
		    mode=elf
		    ;;
		-boot)
		    mode=boot
		    ;;
		*)
		    echo "Usage: $0 {-elf snek-board-1.5.elf} {-boot bootloader-snekboard.bin" 1>&2
		    exit 1
		    ;;
	    esac
	    ;;
	elf)
	    SNEK_FILE="$i"
	    mode=arg
	    ;;
	boot)
	    BOOT_FILE="$i"
	    mode=arg
	    ;;
    esac
done

openocd -f interface/stlink.cfg \
        -c 'transport select hla_swd' \
	-c 'set CHIPNAME at91samd21g18' \
	-c 'set CPUTAPID 0x0bc11477' \
	-f target/at91samdXX.cfg \
	-c init \
	-c 'reset halt' \
	-c 'at91samd bootloader 0' \
	-c "flash write_image erase unlock $BOOT_FILE" \
	-c "flash write_image erase unlock $SNEK_FILE" \
	-c 'reset init' \
	-c 'reset run' \
	-c 'shutdown'
