#! /bin/sh

### The Nice compiler
###
### Copyright 2003 Daniel Bonniot

### The Java Virtual Machine can be specified in the JAVA environment variable.
### Arguments prefixed by -J will be passed to the JVM.


## Locating Nice home

find_home()
{
  PRG="$0"
  # Resolve symlinks.
  while [ -h "$PRG" ]; do
    lsResult=`ls -ld "$PRG"`
    # d'apres expr sous linux, ^ est implicite 
    # au debut de la deuxieme chaine et il ne faut pas le mettre
    link=`expr "$lsResult" : '.*-> \(.*\)$'`
    if expr "$link" : '/.*' > /dev/null; then
        PRG="$link"
    else
        PRG="`dirname $PRG`/$link"
    fi
  done

  APPHOME=`expr "$PRG" : '\(.*\)/bin'`
  if [ -z "${APPHOME}" ]; 
    then APPHOME=`dirname "$PRG"`/..
  fi
}

## Parsing special command line arguments

java=${JAVA-java -Xms8M}
scriptName="$0"
progname=`basename $scriptName`
experimental=false

while true; do 
  case "x$1" in
    x-J*) 
	  java="${java} `expr substr \"$1\" 3 1000`";;
    x-e)  
	  experimental=true ;;
    *) break;;
    esac
  shift
  done

if [ -z "$NICEC_JAR" ]; then
  find_home "$scriptName"
  NICEC_JAR=${APPHOME}/share/java/nice.jar
fi

# Having a trailing ":" at the end of CLASSPATH seems to act as ":." on some platforms.
# We don't want that by default (if CLASSPATH is empty).
if [ -z "${CLASSPATH}" ]; then
    CLASSPATH=${NICEC_JAR}
else
    CLASSPATH=${NICEC_JAR}:${CLASSPATH}
fi

if [ $experimental = true ]; then
    CLASSPATH=${APPHOME}/classes:${APPHOME}/classes.old:${CLASSPATH}
fi

export CLASSPATH

case $progname in
    nicedoc)	class=nice.tools.doc.dispatch          ;;
    niceunit)	class=nice.tools.unit.console.dispatch ;;
    nicec)	class=nice.tools.compiler.console.dispatch

	system_args="--runtime=${NICEC_JAR}"

	gcj="`which gcj 2>/dev/null`"
        # Check the string found is really a file
        # This is a work-around for a bug in OS X: 
        #   `which gcj` returns 0 (success) and prints "no gcj in $PATH"
	if [ -f "$gcj" ]; then
	    system_args="${system_args} --native-compiler=${gcj}"
	fi

esac

# Certain JVMs seem to exit by throwing SIGHUP, thus replacing the exit code
# with 129.
# This happens only when running inside Emacs with Sun's 1.4.2_04-b05.
trap "" SIGHUP

exec ${java} $class ${system_args} "$@"
