#!/bin/bash
# -----------------------------------------------------------------------------
# jruby.sh - Start Script for the JRuby interpreter
#
# Environment Variable Prequisites
#
#   JRUBY_OPTS    (Optional) Default JRuby command line args
#   JRUBY_SHELL   Where/What is system shell
#
#   JAVA_HOME     Must point at your Java Development Kit installation.
#
# -----------------------------------------------------------------------------

cygwin=false

# ----- Identify OS we are running under --------------------------------------
case "`uname`" in
CYGWIN*) cygwin=true
esac

# ----- Verify and Set Required Environment Variables -------------------------

## resolve links - $0 may be a link to  home
PRG=$0
progname=`basename "$0"`

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

JRUBY_HOME_1=`dirname "$PRG"`           # the ./bin dir
JRUBY_HOME=`dirname "$JRUBY_HOME_1"`  # the . dir
# When . == bin and . is in path, need to make home be .. (JRUBY-2699)
#if [ $JRUBY_HOME = '.' ] ; then
# JRUBY_HOME='..'
#fi

if [ -z "$JRUBY_OPTS" ] ; then
  JRUBY_OPTS=""
fi

if [ -z "$JAVA_HOME" ] ; then
  JAVA_CMD='java'
else
  if $cygwin; then
    JAVA_HOME=`cygpath -u "$JAVA_HOME"`
  fi
  JAVA_CMD="$JAVA_HOME/bin/java"
fi

JRUBY_SHELL=/bin/sh

# ----- Set Up The Boot Classpath -------------------------------------------

CP_DELIMETER=":"

# add jruby jars for command-line execution
for j in "$JRUBY_HOME"/lib/jruby*.jar; do
    if [ "$JRUBY_CP" ]; then
        JRUBY_CP="$JRUBY_CP$CP_DELIMETER$j"
        else
        JRUBY_CP="$j"
    fi
done

if $cygwin; then
    JRUBY_CP=`cygpath -p -w "$JRUBY_CP"`
fi

# ----- Set Up The System Classpath -------------------------------------------

if [ "$JRUBY_PARENT_CLASSPATH" != "" ]; then
    # Use same classpath propagated from parent jruby
    CP=$JRUBY_PARENT_CLASSPATH
else
    # add other jars in lib to CP for command-line execution
    for j in "$JRUBY_HOME"/lib/*.jar; do
        if [ "$CP" ]; then
            CP="$CP$CP_DELIMETER$j"
            else
            CP="$j"
        fi
    done

    if $cygwin; then
	CP=`cygpath -p -w "$CP"`
    fi
fi

# ----- Execute The Requested Command -----------------------------------------

if [ -z "$JAVA_MEM" ] ; then
  JAVA_MEM=-Xmx500m
fi

if [ -z "$JAVA_STACK" ] ; then
  JAVA_STACK=-Xss1024k
fi

JAVA_VM=-client

# Split out any -J argument for passing to the JVM.
# Scanning for args is aborted by '--'.
declare -a java_args
declare -a ruby_args
    while [ $# -gt 0 ]
do
    case "$1" in
    # Stuff after '-J' in this argument goes to JVM
    -J*)
        val=${1:2}
        if [ "${val:0:4}" = "-Xmx" ]; then
            JAVA_MEM=$val
        elif [ "${val:0:4}" = "-Xss" ]; then
            JAVA_STACK=$val
        elif [ "${val}" = "" ]; then
            $JAVA_CMD -help
            echo "(Prepend -J in front of these options when using 'jruby' command)" 
            exit
        elif [ "${val}" = "-X" ]; then
            $JAVA_CMD -X
            echo "(Prepend -J in front of these options when using 'jruby' command)" 
            exit
        else
            if [ "${val:0:3}" = "-ea" ]; then
		VERIFY_JRUBY="yes"
	    fi
            java_args=("${java_args[@]}" "${1:2}")
        fi
        ;;
     # Match switches that take an argument
     -e|-I|-S) ruby_args=("${ruby_args[@]}" "$1" "$2"); shift ;;
     # Match same switches with argument stuck together
     -e*|-I*|-S*) ruby_args=("${ruby_args[@]}" "$1" ) ;;
     # Run with the instrumented profiler: http://jiprof.sourceforge.net/
     --profile) 
       PROFILE_ARGS="-javaagent:$JRUBY_HOME/lib/profile.jar -Dprofile.properties=$JRUBY_HOME/lib/profile-ruby.properties" 
       VERIFY_JRUBY="yes"
       ;;
     # Run with the instrumented profiler: http://jiprof.sourceforge.net/
     --profile-all) 
       PROFILE_ARGS="-javaagent:$JRUBY_HOME/lib/profile.jar -Dprofile.properties=$JRUBY_HOME/lib/profile-all.properties" 
       VERIFY_JRUBY="yes"
       ;;
     # Run with JMX management enabled
     --manage)
        java_args=("${java_args[@]}" "-Dcom.sun.management.jmxremote") ;;
     # Run under JDB
     --jdb)
        if [ -z "$JAVA_HOME" ] ; then
          JAVA_CMD='jdb'
        else
          if $cygwin; then
            JAVA_HOME=`cygpath -u "$JAVA_HOME"`
          fi
          JAVA_CMD="$JAVA_HOME/bin/jdb"
        fi ;;
     --client)
        JAVA_VM=-client ;;
     --server)
        JAVA_VM=-server ;;
     --sample)
        java_args=("${java_args[@]}" "-Xprof") ;;
     --1.9)
        java_args=("${java_args[@]}" "-Djruby.compat.version=RUBY1_9") ;;
     --1.8)
        java_args=("${java_args[@]}" "-Djruby.compat.version=RUBY1_8") ;;
     # Abort processing on the double dash
     --) break ;;
     # Other opts go to ruby
     -*) ruby_args=("${ruby_args[@]}" "$1") ;;
     # Abort processing on first non-opt arg
     *) break ;;
    esac
    shift
done

# Add a property to report memory max
JAVA_OPTS="$JAVA_OPTS $JAVA_VM -Djruby.memory.max=${JAVA_MEM:4} -Djruby.stack.max=${JAVA_STACK:4}"

# Append the rest of the arguments
ruby_args=("${ruby_args[@]}" "$@")

# Put the ruby_args back into the position arguments $1, $2 etc
set -- "${ruby_args[@]}"

JAVA_OPTS="$JAVA_OPTS $JAVA_MEM $JAVA_STACK"

if $cygwin; then
  JRUBY_HOME=`cygpath --mixed "$JRUBY_HOME"`
  JRUBY_SHELL=`cygpath --mixed "$JRUBY_SHELL"`
  
  if [[ ( "${1:0:1}" = "/" ) && ( ( -f "$1" ) || ( -d "$1" )) ]]; then
    win_arg=`cygpath -w "$1"`
    shift
    win_args=("$win_arg" "$@")
    set -- "${win_args[@]}"
  fi
fi

if [ "$VERIFY_JRUBY" != "" ]; then
  if [ "$PROFILE_ARGS" != "" ]; then
      echo "Running with instrumented profiler"
  fi

  $JAVA_CMD $PROFILE_ARGS $JAVA_OPTS "${java_args[@]}" -classpath "$JRUBY_CP$CP_DELIMETER$CP$CP_DELIMETER$CLASSPATH" \
    "-Djruby.home=$JRUBY_HOME" \
    "-Djruby.lib=$JRUBY_HOME/lib" -Djruby.script=jruby \
    "-Djruby.shell=$JRUBY_SHELL" \
    org.jruby.Main $JRUBY_OPTS "$@"

  # Record the exit status immediately, or it will be overridden.
  JRUBY_STATUS=$?

  if [ "$PROFILE_ARGS" != "" ]; then
      echo "Profiling results:"
      cat profile.txt
  fi

  exit $JRUBY_STATUS
else
  exec "$JAVA_CMD" $JAVA_OPTS "${java_args[@]}" -Xbootclasspath/a:"$JRUBY_CP" -classpath "$CP$CP_DELIMETER$CLASSPATH" \
    "-Djruby.home=$JRUBY_HOME" \
    "-Djruby.lib=$JRUBY_HOME/lib" -Djruby.script=jruby \
    "-Djruby.shell=$JRUBY_SHELL" \
    org.jruby.Main $JRUBY_OPTS "$@"
fi

# Be careful adding code down here, you might override the exit
# status of the jruby invocation.
