#!/bin/sh

SHAREDIR="/usr/share/snek"

SNEKHEX="$SHAREDIR/snek-nano-every-1.13.hex"

RESET="$SHAREDIR/snek-nano-every-reset-port"
action="default"

PORT="/dev/ttyACM0"

# Convert end of code from bytes to flash pages (256 byte units)
ATMEGA_CODE_SIZE=`echo "0xb000" | sed 's/00$//'`

mode=arg

action=load

for i in "$@"; do
    case "$mode" in
	arg)
	    case "$i" in
		load|fuse|fuseload)
		    action="$i"
		    ;;
		-hex|--hex)
		    mode=hex
		    ;;
		-port|--port)
		    mode=port
		    ;;
		-reset|--reset)
		    mode=reset
		    ;;
		*)
		      echo "Usage: $0 {-hex snek-nano-every.hex} {-port /dev/ttyACM0}" 1>&2
		      exit 1
		      ;;
	    esac
	    ;;
	hex)
	    SNEKHEX="$i"
	    mode=arg
	    ;;
	port)
	    PORT="$i"
	    mode=arg
	    ;;
	reset)
	    RESET="$i"
	    mode=arg
    esac
done

echo "$RESET" "$PORT"
"$RESET" "$PORT"

fuse="-Ufuse2:w:0x02:m -Ufuse5:w:0xC9:m -Ufuse8:w:$ATMEGA_CODE_SIZE:m -Ufuse7:w:$ATMEGA_CODE_SIZE:m"
case $action in
    fuse)
	echo avrdude -P $PORT -c jtag2updi -b 115200 -p atmega4809 "$fuse"
	avrdude -P $PORT -c jtag2updi -b 115200 -p atmega4809 "$fuse"
	;;
    load)
	echo avrdude -P $PORT -c jtag2updi -b 115200 -p atmega4809 -U flash:w:"${SNEKHEX}"
	avrdude -P $PORT -c jtag2updi -b 115200 -p atmega4809 -U flash:w:"${SNEKHEX}"
	;;
    fuseload)
	echo avrdude -P $PORT -c jtag2updi -b 115200 -p atmega4809 $fuse -U flash:w:"${SNEKHEX}"
	avrdude -P $PORT -c jtag2updi -b 115200 -p atmega4809 $fuse -U flash:w:"${SNEKHEX}"
	;;
esac
