#!/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.
#
# This is a quick and dirty hack and probably only works with bison invocations
# that include -d, with paths that don't include spaces.  It doesn't bother to
# trim the cache.

set -e

bison="$1"
shift
args="$@"

for arg in $args ; do
    case $arg in
		"--version")
			$bison $args
			exit
			;;
		"-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
	echo "could not find .y file in command line arguments: $args"
	exit 1
fi

if [ -z "$c_file" ] ; then
	c_file="(echo "$y_file" | sed 's/\.y/.tab.c/')"
fi

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

h_file="$(echo $c_file | sed 's/\.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 [ ! -e "$cached_c_file" -o ! -e "$cached_h_file" ] ; then
	$bison $args
	cp "$c_file" "$cached_c_file"
	cp "$h_file" "$cached_h_file"
else
	cp "$cached_c_file" "$c_file"
	cp "$cached_h_file" "$h_file"
fi
