#!/bin/bash

set -e

CHANGED=false

cd $(dirname $0)/..

# Rebuild the grammar if necessary.
if [ src/ohm-grammar.ohm -nt dist/ohm-grammar.js ]; then
  src/ohm-cmd.js src/ohm-grammar.ohm > dist/ohm-grammar.js.new
  mv -f dist/ohm-grammar.js.new dist/ohm-grammar.js
  CHANGED=true
fi

# Rebuild the built-in rules if necessary.
if [ "$CHANGED" == "true" ] || [ src/built-in-rules.ohm -nt dist/built-in-rules.js ]; then
  src/ohm-cmd.js src/built-in-rules.ohm > dist/built-in-rules.js.new
  mv -f dist/built-in-rules.js.new dist/built-in-rules.js
  CHANGED=true
fi

# Run the tests if one of the files changed and the `--test` argument is set.
if [ "$CHANGED" == "true" ] && [ "$1" == "--test" ]; then
  npm test --silent
fi

echo 'Bootstrap complete.'
