#!/bin/sh

# Extract annotations from a class file and write them to an annotation file.
# For usage information, run: extract-annotations --help
# See the Annotation File Utilities documentation for more information.

# A few options are consumed by this script rather than being passed to the
# underlying Java program.  They must be the first command-line arguments
# provided.
DEBUG=0
# CLASSPATH=${CLASSPATH}
while [ "$#" -gt 0 ]; do
  case "$1" in
    --debug-script)
      # Debug this script
      DEBUG=1
      shift
      ;;
    -cp | -classpath)
      # Set the classpath
      CLASSPATH=$2
      shift 2
      ;;
    *)
      break
      ;;
  esac
done

AFU=${AFU:-$(dirname "$0")/..}
ANNOTATION_FILE_UTILS=${AFU}/dist/annotation-file-utilities-all.jar

JAVAC_JAR=${JAVAC_JAR:-${AFU}/lib/javac-9+181-r4173-1.jar}

if java -version 2>&1 | grep version | grep 1.8 > /dev/null; then
  # Using JDK 8. -Xbootclasspth isn't supported in 9+ and isn't required.
  BOOTCLASSPATH=-Xbootclasspath/p:${JAVAC_JAR}
  JDK_OPENS=
else
  BOOTCLASSPATH=
  # Need open to access CommandLine.parse dynamically to check its type:
  JDK_OPENS="--add-opens jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED --add-opens jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED --add-opens jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED --add-opens jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED  --add-opens jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED --add-opens jdk.internal.opt/jdk.internal.opt=ALL-UNNAMED"
fi

if [ "$DEBUG" = "1" ]; then
  echo "--- start of extract-annotations debugging output"
  echo "AFU=${AFU}"
  echo "ANNOTATION_FILE_UTILS=${ANNOTATION_FILE_UTILS}"
  echo "CLASSPATH=${CLASSPATH}"
  # Keep this in sync with the actual command below.
  # shellcheck disable=SC2086 # ${BOOTCLASSPATH} and ${JDK_OPENS} might be empty and must NOT be quoted.
  echo java -ea ${BOOTCLASSPATH} ${JDK_OPENS} -cp "${ANNOTATION_FILE_UTILS}:${CLASSPATH}" org.checkerframework.afu.scenelib.io.classfile.ClassFileReader "$@"
  echo "--- end of extract-annotations debugging output"
fi

# Needs CLASSPATH to find user files
# shellcheck disable=SC2086 # ${BOOTCLASSPATH} and ${JDK_OPENS} might be empty and must NOT be quoted.
java -ea ${BOOTCLASSPATH} ${JDK_OPENS} -cp "${ANNOTATION_FILE_UTILS}:${CLASSPATH}" org.checkerframework.afu.scenelib.io.classfile.ClassFileReader "$@"
