#!/bin/sh

SHAREDIR="/usr/share/snek"

SNEKUDUINOBASE="$SHAREDIR/snek-uduino"
SNEKUDUINOREST="-1.5.hex"
SNEKUDUINO="$SNEKUDUINOBASE""$SNEKUDUINOREST"

action="fuseload"

ISP=usbtiny

mode=arg

verify=""

for i in "$@"; do
    case "$mode" in
	arg)
	    case "$i" in
		fuse|load|fuseload)
		    action="$i"
		    ;;
		-isp|--isp)
		    mode=isp
		    ;;
		-hex|--hex)
		    mode=hex
		    ;;
		-quick)
		    verify="-V"
		    ;;
		*)
		      echo "Usage: $0 {-isp usbtiny} {-isp avrisp2} {-hex snek-uduino.hex} {fuseload|load|fuse}" 1>&2
		      exit 1
		      ;;
	    esac
	    ;;
	isp)
	    ISP="$i"
	    mode=arg
	    ;;
	hex)
	    SNEKUDUINO="$i"
	    mode=arg
	    ;;
    esac
done

FUSES="-U lfuse:w:0xff:m -U hfuse:w:0x91:m -U efuse:w:0xfd:m"

case "$action" in
    fuse)
	avrdude -V -c $ISP -p m32u4 -u $FUSES
	;;
    fuseload)
	avrdude -V -c $ISP -p m32u4 -u $FUSES && avrdude $verify -c $ISP -p m32u4 -U flash:w:"${SNEKUDUINO}"
	;;
    load)
	avrdude $verify -c $ISP -p m32u4 -U flash:w:"${SNEKUDUINO}"
	;;
esac
