#!/bin/bash

TARGET_DIRECTORY=..
GENERATE_FILES=false
BASE_DIRECTORY=../../../..
LINUX_RES_JAR_PATH=$BASE_DIRECTORY/linux-res/bin/antlr-3.4-complete.jar
SOURCE_FILE=MySQL.g
SOURCE_FILE2=MySQLSimpleParser.g


if [ ! -f "$TARGET_DIRECTORY/MySQLLexer.c" ]  || [ $SOURCE_FILE -nt "$TARGET_DIRECTORY/MySQLLexer.c" ];  then GENERATE_FILES=true; fi
if [ ! -f "$TARGET_DIRECTORY/MySQLLexer.h" ]  || [ $SOURCE_FILE -nt "$TARGET_DIRECTORY/MySQLLexer.h" ];  then GENERATE_FILES=true; fi
if [ ! -f "$TARGET_DIRECTORY/MySQLParser.c" ] || [ $SOURCE_FILE -nt "$TARGET_DIRECTORY/MySQLParser.c" ]; then GENERATE_FILES=true; fi
if [ ! -f "$TARGET_DIRECTORY/MySQLParser.h" ] || [ $SOURCE_FILE -nt "$TARGET_DIRECTORY/MySQLParser.h" ]; then GENERATE_FILES=true; fi
if [ ! -f "$TARGET_DIRECTORY/MySQLSimpleParser.c" ] || [ $SOURCE_FILE -nt "$TARGET_DIRECTORY/MySQLSimpleParser.c" ]; then GENERATE_FILES=true; fi
if [ ! -f "$TARGET_DIRECTORY/MySQLSimpleParser.h" ] || [ $SOURCE_FILE -nt "$TARGET_DIRECTORY/MySQLSimpleParser.h" ]; then GENERATE_FILES=true; fi

if [ $GENERATE_FILES == true ]; then
  # Check if the supplied file exists
  if [ ! -f "$ANTLR_JAR_PATH" ]; then
    # Check the default development path
    if [ -f "$LINUX_RES_JAR_PATH" ]; then
      ANTLR_JAR_PATH="$LINUX_RES_JAR_PATH"
    else
      echo "The antlr-3.4-complete.jar file could not be found."
      echo "Please make sure that linux-res is in `cd $BASE_DIRECTORY; pwd` or add the ANTLR_JAR_PATH enviroment variable with the path to the file."
      echo "You'll also need Java Runtime Enviroment installed, so the parser files can be regenerated."
      exit 1
    fi
  fi

  java -Xmx1024m -jar "$ANTLR_JAR_PATH" -make $SOURCE_FILE -o $TARGET_DIRECTORY -Xmaxswitchcaselabels 30
  java -Xmx1024m -jar "$ANTLR_JAR_PATH" -make $SOURCE_FILE2 -o $TARGET_DIRECTORY -Xmaxswitchcaselabels 30
fi

