#!/bin/bash

# This is a wrapper for javac

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

if [ -z "$INFER_OLD_PATH" ]; then
    echo '$INFER_OLD_PATH with a copy of $PATH not provided.' > /dev/stderr
    exit 1
fi

HOST_COMPILER=(`PATH="$INFER_OLD_PATH" which javac`)
COMPILER_ARGS=("$@")
HOST_COMPILER_COMMAND=("$HOST_COMPILER" "${COMPILER_ARGS[@]}")
FRONTEND_COMMAND=("$SCRIPT_DIR/../../bin/infer" "capture" "--continue"
                  "--" "javac" "${COMPILER_ARGS[@]}")

if [[ "$*" == *-version* ]]; then
    exec "${HOST_COMPILER_COMMAND[@]}"
elif [ "$INFER_COMPILER_WRAPPER_IN_RECURSION" != "1" ]; then
    export INFER_COMPILER_WRAPPER_IN_RECURSION="1"
    PATH="$INFER_OLD_PATH" exec "${FRONTEND_COMMAND[@]}"
else
    echo 'ERROR: the javac wrapper called itself!' > /dev/stderr
    # internal error
    exit 3
fi
