#!/usr/bin/env bash

#set -o nounset ; set -o errexit

# 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"
default_java_opts="-Xmx768m -Xms768m"
withCompiler=true

CompilerMain=dotty.tools.dotc.Main
DecompilerMain=dotty.tools.dotc.decompiler.Main
ReplMain=dotty.tools.repl.Main
ScriptingMain=dotty.tools.scripting.Main
JVM_CP_ARGS="$PROG_HOME/lib/scaladoc.jar"

PROG_NAME=$CompilerMain

addJava () {
  java_args+=("'$1'")
}
addScala () {
  scala_args+=("'$1'")
}
addResidual () {
  residual_args+=("'$1'")
}
addScrip() {
  script_args+=("'$1'")
}

#for A in "$@" ; do echo "A[$A]" ; done ; exit 2

while [[ $# -gt 0 ]]; do
case "$1" in
           --) shift; for arg; do addResidual "$arg"; done; set -- ;;
  -v|-verbose) verbose=true && addScala "-verbose" && shift ;;
    -q|-quiet) quiet=true && shift ;;

      -colors) colors=true && shift ;;
   -no-colors) unset colors && shift ;;
          # break out -D and -J options and add them to java_args so
          # they reach the JVM in time to do some good. The -D options
          # will be available as system properties.
          -D*) addJava "$1" && shift ;;
          -J*) addJava "${1:2}" && shift ;;
            *) addResidual "$1"
               shift
               ;;
  esac
done

eval "\"$JAVACMD\"" \
     ${JAVA_OPTS:-$default_java_opts} \
     "${java_args[@]}" \
     -classpath "${JVM_CP_ARGS}" \
      -Dscala.expandjavacp=true \
      -Dscala.usejavacp=true \
     "dotty.tools.scaladoc.Main"  \
     "${scala_args[@]}" \
     "${residual_args[@]}" \
     "${scripting_string-}"
scala_exit_status=$?
onExit
