#!/bin/sh

SHAREDIR="/usr/share/snek"

SNEKDUINO="$SHAREDIR/snek-duemilanove-1.4.1.hex"

action="default"

ISP=optiboot

ISPPORT=""

mode=arg

for i in "$@"; do
    case "$mode" in
	arg)
	    case "$i" in
		fuse|load|fuseload)
		    action="$i"
		    ;;
		-isp|--isp)
		    mode=isp
		    ;;
		-hex|--hex)
		    mode=hex
		    ;;
		-port|--port)
		    mode=port
		    ;;
		*)
		      echo "Usage: $0 {-isp optiboot} {-isp usbtiny} {-isp avrisp2} {-isp arduinoisp} {-hex snek-duemilanove.hex} {-port /dev/ttyUSB0} {fuseload|load|fuse}" 1>&2
		      exit 1
		      ;;
	    esac
	    ;;
	isp)
	    ISP="$i"
	    mode=arg
	    ;;
	hex)
	    SNEKDUINO="$i"
	    mode=arg
	    ;;
	port)
	    ISPPORT="-P $i"
	    mode=arg
    esac
done

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

case "$ISP" in
    optiboot)
    # For optiboot, use arduino at 115200 baud
    [ "$ISPPORT" ] || ISPPORT="-P /dev/ttyUSB0"
    AVRDUDE="avrdude $ISPPORT -c arduino -b 115200 -p ATMEGA328P"
    case "$action" in
	fuse|fuseload)
	    echo "$0: optiboot can't set fuses" 1>&2
	    exit 1
	    ;;
	default)
	    action="load"
	    ;;
    esac
    ;;
    arduinoisp)
    # For ArdinoISP, use avrisp + 19200 baud...
    [ "$ISPPORT" ] || ISPPORT="-P /dev/ttyUSB0"
    AVRDUDE="avrdude $ISPPORT -c avrisp -b 19200 -p ATMEGA328P"
    ;;
    *)
    AVRDUDE="avrdude $ISPPORT -c $ISP -p ATMEGA328P"
    ;;
esac


case "$action" in
    fuse)
	$AVRDUDE -V -u $FUSES
	;;
    default|fuseload)
	$AVRDUDE -V -u $FUSES && $AVRDUDE -U flash:w:"${SNEKDUINO}"
	;;
    load)
	$AVRDUDE -U flash:w:"${SNEKDUINO}"
	;;
esac
