#!/bin/sh

HOME_DIR=`dirname $0`/..

# Given the "java" executable as an argument, find JAVA_HOME
find_java() {
  # First check if it is a JDK in the /usr/lib/jvm directory, or a symlink there.
  # The test is somewhat complicated due to the different ways the Java implementations
  # are set up with the alternatives system
  # e.g.
  #  /usr/bin/java -> /etc/alternatives/java -> /usr/lib/jvm/java-1.5.0-sun/jre/bin/java
  # or
  #  /usr/bin/java -> /etc/alternatives/java -> /usr/lib/jvm/java-gcj/bin/java -> /usr/bin/gij-4.2

  JAVA_HOME=$1
  while true ; do
    case $JAVA_HOME in
      /usr/lib/jvm/*)
        # Found it! Return the correct paremt directory.

        JAVA_HOME=`echo $JAVA_HOME | sed 's:\(/usr/lib/jvm/[^/]*\).*:\1:'`
	return
	;;
      *) ;;
    esac

    if [ -h $JAVA_HOME ] ; then
      JAVA_HOME=`readlink $JAVA_HOME`
    else
      break
    fi
  done
        
  # Not found in the Debian alternatives system, so presumably
  # it is a user-installed JDK/JRE. Might as well be helpful
  # and try to find JAVA_HOME.

  # First try for a JDK:
  JAVA_HOME=`readlink -e $1`
  while [ `dirname $JAVA_HOME` != /  ]; do
    if [ -e $JAVA_HOME/lib/tools.jar ]; then
      return
    fi

    JAVA_HOME=`dirname $JAVA_HOME`
  done

  # If we get here we did not find a JDK. Search again for a JRE:
  JAVA_HOME=`readlink -e $1`
  while [ `dirname $JAVA_HOME` != /  ]; do
    if [ -e $JAVA_HOME/bin/java ]; then
      return
    fi

    JAVA_HOME=`dirname $JAVA_HOME`
  done

  # Nothing found; leave blank
  JAVA_HOME=
}

if [ -z "$JAVA_HOME" ] ; then
  if [ -r /etc/gentoo-release ] ; then
    JAVA_HOME=`java-config --jre-home`
  else
    # Debian patch - search for preferred JRE
    if [ -n "$JAVACMD" ] ; then
      find_java "$JAVACMD"
    else
      find_java `which java`
    fi
  fi
fi

if [ -z "$JAVACMD" ] ; then
  if [ -n "$JAVA_HOME"  ] ; then
    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
      # IBM's JDK on AIX uses strange locations for the executables
      JAVACMD="$JAVA_HOME/jre/sh/java"
    else
      JAVACMD="$JAVA_HOME/bin/java"
    fi
  else
    JAVACMD="`which java`"
  fi
fi

if [ ! -x "$JAVACMD" ] ; then
  echo "Error: JAVA_HOME is not defined correctly."
  echo "  We cannot execute $JAVACMD"
  exit 1
fi

if [ -z "$JAVA_HOME" ] ; then
  echo "Warning: JAVA_HOME environment variable is not set."
fi

cd ${HOME_DIR}

JAR_FILE=`find . -type f -name 'autoquest-runner-*.jar'`

if [ ! -f "$JAR_FILE" ] ; then
  echo "Error: Could not find executable jar file in distribution."
  echo "  Execution aborted."
  exit 1
fi

exec "$JAVACMD" -jar "${JAR_FILE}" $*
