#!/bin/sh
#
# A very dumb wrapper script that understands how to cache the output of bison
# invocations, a bit like ccache.  We don't need to do any kind of clever
# dependency analysis.
#
# XXX: Doesn't trim the cache yet.
# XXX: Assumes the real bison can be invoked with "bison".

set -e

case "$OSTYPE" in
    darwin*)
        md5sum="md5 -q"
	;;
    *)
        md5sum="md5sum"
	;;
esac

bison="bison"

for arg in "$@" ; do
    case $arg in
		"--version")
			$bison "$@"
			exit
			;;
		"-d")
			make_h_file=1
			;;
		"-o")
			next_is_c_file=1
			;;
		"-"*)
			;;
		*)
			if [ "$next_is_c_file" = "1" ] ; then
				c_file="$arg"
				next_is_c_file=0
			else
				y_file="$arg"
			fi
			;;
	esac
done

if [ -z "$y_file" ] ; then
	# cannot work without an input file
	echo "could not find .y file in command line arguments: $@"
	exit 1
fi

if [ -z "$c_file" ] ; then
	# default name for output file, if user didn't provide one
	c_file="${y_file%.y}.tab.c"
fi

if [ -z "$SIMPLE_BISON_CACHE_PATH" ] ; then
	SIMPLE_BISON_CACHE_PATH="/tmp/simple-bison-cache"
fi

h_file="${c_file%.c}.h"
y_file_hash="$($md5sum "$y_file" | cut -d' ' -f1)"
cached_c_file="$SIMPLE_BISON_CACHE_PATH/$y_file_hash.c"
cached_h_file="$SIMPLE_BISON_CACHE_PATH/$y_file_hash.h"

mkdir -p "$SIMPLE_BISON_CACHE_PATH"

if [ "$make_h_file" = "1" -a -e "$cached_c_file" -a -e "$cached_h_file" ] ; then
	cp "$cached_c_file" "$c_file"
	cp "$cached_h_file" "$h_file"
elif [ -z "$make_h_file" -a -e "$cached_c_file" ] ; then
	cp "$cached_c_file" "$c_file"
else
	$bison "$@"
	cp "$c_file" "$cached_c_file"
	if [ "$make_h_file" = "1" ] ; then
		cp "$h_file" "$cached_h_file"
	fi
fi
