#!/bin/sh

# rhino discards the path to the current script file, so we must add it back
SOURCE="$0"
while [ -h "$SOURCE" ] ; do SOURCE="$(readlink "$SOURCE")"; done
# Get a Windows path under MinGW or Cygwin
BASEPATH="$( cd -P "$( dirname "$SOURCE" )" && (pwd -W 2>/dev/null || cygpath -w $(pwd) 2>/dev/null || pwd))"
if [ "${BASEPATH%${BASEPATH#?}}" != "/" ] ; then
  BASEPATH="$( echo "$BASEPATH" | sed -e 's@\\@/@g' )"
  # We need a extra slash for URLs
  UBASEPATH="/$BASEPATH"
else
  UBASEPATH="$BASEPATH"
fi

# for whatever reason, Rhino requires module paths to be valid URIs
URLPATH="file://$UBASEPATH"
URLPATH=`echo "$URLPATH" | sed -e 's/ /%20/g'`
ENCODEDBASEPATH=`echo "$BASEPATH" | sed -e 's/ /%20/g'`

ARGS="$@"

if test "$1" = "--debug"
then
    echo "Running Debug"
    CMD="org.mozilla.javascript.tools.debugger.Main -debug"
    # strip --debug argument
    length=$(($#-1))
    ARGS=${@:2:$length}
else
    CMD="org.mozilla.javascript.tools.shell.Main"
fi

#Conditionally execute different command lines depending on whether we're running tests or not
if test "$1" = "-T"
then
    echo "Running Tests"
    cd -P "$(dirname "$SOURCE")"
    java -classpath "${BASEPATH}/rhino/js.jar" ${CMD} -opt -1 -modules "${URLPATH}/node_modules" -modules "${URLPATH}/rhino" -modules "${URLPATH}/lib" -modules "${URLPATH}" "${BASEPATH}/jsdoc.js" $ARGS --dirname="${BASEPATH}/" 

else
    # normal mode should be quiet
    java -classpath "${BASEPATH}/rhino/js.jar" ${CMD} -modules "${URLPATH}/node_modules" -modules "${URLPATH}/rhino" -modules "${URLPATH}/lib" -modules "${URLPATH}" "${BASEPATH}/jsdoc.js" $ARGS --dirname="${BASEPATH}/" 
fi
