#!/bin/bash
#
# This script runs jflex generating java code based on .jflex files.
# jflex tool itself resides in external/jflex. At the time of this writing
# it's not a part of jflex manifest and needs to be checked out manually.
#
# The script can be run from anywhere (it does not depend on current working directory)
# Set $JFLEX to overwrite jflex location, if desired
#
# After making any changes to the lexer, the update source file(s) generated by
# this script should be checked in to the repository

# Update when switching to a different version of jflex
EXPECTED_JFLEX_VERSION="1.6.1"
EXPECTED_JFLEX_VERSION_STR="This is JFlex $EXPECTED_JFLEX_VERSION"

# Get the location of this script used to find locations of other things in the tree.
SCRIPT_DIR=`dirname $0`
echo $SCRIPT_DIR

TOP_PATH="$SCRIPT_DIR/../../.."

# Run the java jar when 'JFLEX' is not in the environment
function exec_jar_jflex {
  java -jar "$jflex_location" "$@"
}

# All specifying jflex but fallback to default location
if [ -z  "$JFLEX" ]
then
  # Best effort to find it inside of the gradle cache
  jflex_jar_name="jflex-${EXPECTED_JFLEX_VERSION}.jar"
  jflex_location="$(find $HOME/.gradle/caches/modules-* -name "$jflex_jar_name" | head -n 1)"
  if [ -z $jflex_location ]; then
    echo "ERROR: Could not find jflex location, consider setting the \$JFLEX variable to point to it"
    exit 1
  fi
  JFLEX=exec_jar_jflex
fi

JFLEX_VERSION=`"$JFLEX" --version`

if [ "$JFLEX_VERSION" = "" ]
then
  echo "ERROR: Failed to execute jflex at \"$JFLEX\", \"$jflex_location\""
  exit 1
fi

if [ "$EXPECTED_JFLEX_VERSION_STR" != "$JFLEX_VERSION" ]
then
  echo "ERROR: Wrong version of jflex: \"$JFLEX_VERSION\". Expected: \"$EXPECTED_JFLEX_VERSION_STR\""
  exit 1
fi

JAVA_FILE=$SCRIPT_DIR/src/main/java/com/android/tools/smali/smali/smaliFlexLexer.java
rm -f "$JAVA_FILE"

"$JFLEX" --nobak -d "$SCRIPT_DIR/src/main/java/com/android/tools/smali/smali" "$SCRIPT_DIR/src/main/jflex/smaliLexer.jflex"

# delete trailing space from end of each line to make gerrit happy
sed 's/[ ]*$//' "$JAVA_FILE" > "$JAVA_FILE.tmp"
rm "$JAVA_FILE"
mv "$JAVA_FILE.tmp" "$JAVA_FILE"