#!/bin/bash

# ----------------------------------------------------------------
# Setup
us=$(basename $0)
set -euo pipefail

verbose="false"

if [ $# -eq 1 ]; then
  bnf="$1"
elif [ $# -eq 2 ]; then
  if [ "$1" = "-v" ]; then
    verbose="true"
  else
    echo "Usage: $0 {.bnf file}" 1>&2
    exit 1
  fi
  bnf="$2"
else
  echo "Usage: $0 {.bnf file}" 1>&2
  exit 1
fi

dir=src/parsing
mkdir -p $dir

# ----------------------------------------------------------------
# Run the parser-generator

# Build the bin/gocc executable:
go get github.com/goccmack/gocc
#go get github.com/johnkerl/gocc
bingocc="$GOPATH/bin/gocc"
if [ ! -x "$bingocc" ]; then
  exit 1
fi

rm -f $dir/*.txt
if [ "$verbose" = "true" ]; then
  lr1="$dir/LR1_conflicts.txt"
  # The -o specifies the package name within the autogen
  $bingocc -v -o $dir $bnf || expand -2 $lr1
else
  $bingocc -o $dir $bnf
fi

echo "Parser-autogen OK"

# Code-gen directories:
#   $dir/errors/
#   $dir/lexer/
#   $dir/parser/
#   $dir/token/
#   $dir/util/

# ----------------------------------------------------------------
# Override GOCC codegen with customized error handling
cp ../../../go/src/parsing/errors.go.template src/parsing/errors/errors.go
sed -i .bak 's:miller/src:two/src:' src/parsing/errors/errors.go

# ----------------------------------------------------------------
# Copy AST files from the main Miller tree

rm -rf ./src/lib/
rm -rf ./src/dsl/

mkdir -p ./src/lib/
mkdir -p ./src/dsl/

cp ../../../go/src/lib/*.go ./src/lib/
cp ../../../go/src/dsl/ast*.go ./src/dsl/

# Different path to autogen between main Miller tree and here
sed -i .bak 's:miller/src:two/src:' src/dsl/ast*go

# ----------------------------------------------------------------
# Compile the main and the parser-autogen

go build main.go
echo "Compile OK"
