#!/usr/bin/env bash

# Try to autodetect real location of the script
if [ -z "${PROG_HOME-}" ] ; then
  ## resolve links - $0 may be a link to PROG_HOME
  PRG="$0"

  # need this for relative symlinks
  while [ -h "$PRG" ] ; do
    ls=`ls -ld "$PRG"`
    link=`expr "$ls" : '.*-> \(.*\)$'`
    if expr "$link" : '/.*' > /dev/null; then
      PRG="$link"
    else
      PRG="`dirname "$PRG"`/$link"
    fi
  done

  saveddir=`pwd`

  PROG_HOME=`dirname "$PRG"`/..

  # make it fully qualified
  PROG_HOME=`cd "$PROG_HOME" && pwd`

  cd "$saveddir"
fi

source "$PROG_HOME/libexec/common"

[ -z "$PROG_NAME" ] && PROG_NAME=$CompilerMain

while [[ $# -gt 0 ]]; do
  case "$1" in
    --)
      # pass all remaining arguments to scala, e.g. to avoid interpreting them here as -D or -J
      while [[ $# -gt 0 ]]; do addScala "$1" && shift ; done
      ;;
    -script)
      # pass all remaining arguments to scala, e.g. to avoid interpreting them here as -D or -J
      while [[ $# -gt 0 ]]; do addScala "$1" && shift ; done
      ;;
    # Optimize for short-running applications, see https://github.com/scala/scala3/issues/222
    -Oshort)
      addScala "-Oshort" && \
      addJava "-XX:+TieredCompilation" && addJava "-XX:TieredStopAtLevel=1" && shift ;;
    -D*)
      # pass to scala as well: otherwise we lose it sometimes when we
      # need it, e.g. communicating with a server compiler.
      # respect user-supplied -Dscala.usejavacp
      addJava "$1"
      addScala "$1"
      shift
      ;;
    -J*)
      # as with -D, pass to scala even though it will almost
      # never be used.
      addJava "${1:2}"
      addScala "$1"
      shift
      ;;
    -classpath*)
      if [ "$1" != "${1##* }" ]; then
        # -classpath and its value have been supplied in a single string e.g. "-classpath 'lib/*'"
        A=$1 ; shift # consume $1 before adding its substrings back
        set -- $A "$@" # split $1 on whitespace and put it back
      else
        addScala "$1"
        shift
      fi
      ;;
    *)
      addScala "$1"
      shift
      ;;
  esac
done

compilerJavaClasspathArgs

[ -n "$script_trace" ] && set -x
[ -z "${ConEmuPID-}" -o -n "${cygwin-}" ] && export MSYSTEM= PWD= # workaround for #12405

# exec here would prevent onExit from being called, leaving terminal in unusable state
eval "\"$JAVACMD\"" \
   ${JAVA_OPTS:-$default_java_opts} \
   "${java_args[@]}" \
   "-classpath \"$jvm_cp_args\"" \
   "-Dscala.expandjavacp=true" \
   "-Dscala.usejavacp=true" \
   "-Dscala.home=\"$PROG_HOME\"" \
   "dotty.tools.MainGenericCompiler" \
   "${scala_args[@]}"

scala_exit_status=$?
onExit
