#!/bin/bash

rm -f /tmp/1 /tmp/2

objcopy -Iihex "$*" --gap-fill=0xff -Obinary /tmp/1
echo "Searching for match..."
git checkout master
git show -q --oneline --decorate

exitnomatch=0
target=bs_nfet.hex

while make "$target" > /dev/null && objcopy -Iihex "$target" --gap-fill=0xff -Obinary /tmp/2; do
	cmp -s /tmp/[12]
	cmp="$?"
	if [ $cmp -eq 2 ]; then
		echo "cmp failed"
		exit 2
	elif [ $cmp -eq 0 ]; then
		echo MATCH
		exitnomatch=1
	elif [ $cmp -eq 1 ]; then
		if [ $exitnomatch -eq 1 ]; then
			echo "Match diverged: reversing and exiting."
			git checkout -q 'HEAD@{1}' > /dev/null
			git show -q --oneline --decorate
			make "$target"
			exit 0
		fi
	fi
	git checkout -q HEAD^ > /dev/null || exit 0
	git show -q --oneline --decorate
done
