#!/bin/sh

cache=$HOME/.blindfold/compiled-grammars/
executable=./blindfold

in=$1
echo "$0 in:  $1"  1>&2
# Perform a command, after echoing it, and abort if it fails.
run () { echo "RUNNING $@" 1>&2 ; if ! "$@"; then exit 1; fi; }


if [ ! -d $cache ]; then
  mkdir --mode=700 --parents $cache
fi


if ! hash=`sha1sum $1 | cut -c1-40`; then
  if ! hash=`md5sum $1 | cut -c1-32`; then
    # give up and just make something unique
    $hash=date +%Y-%m-%dT%H:%M:%S-$$
  fi
fi
  
out=$cache$hash.so

# should compare against timestamp on parser_common_head, etc.
# OR.... just put those in the grammar file!
if [ ! -f $out -o $out -ot $executable ] ; then

#ytab=y.tab
#yacc=yacc
ytab=y_tab
yacc="btyacc -l -v -t"

run $yacc $in

run g++ -g -c ${ytab}.c -I`pwd`

# I have no clue why I need certain object files here, while other
# ones seem to be resolved from my executable just fine.  Maybe it has
# to do with how/whether they are used in the executable?  

run g++ -ldl -g -shared -Wl,-export-dynamic -o $out ${ytab}.o

echo "GRAMMAR compile script ends successfully."  1>&2

fi

echo $0 out: $out 1>&2
echo RESULT=$out

exit 0