#!/bin/bash

# Having any sort of classpath causes massive breakage, with Kaffe at least.
unset CLASSPATH; export CLASSPATH
unset JAVA_HOME; export JAVA_HOME
unset WORKSPACE; export WORKSPACE

# Make sure this directory exists.
if [ ! -d ~/.eclipse ]; then
    mkdir ~/.eclipse > /dev/null 2> /dev/null
    if [ $? -ne 0 ]; then
        echo "Could not create ~/.eclipse." 1>&2
        exit $?
    fi
fi

# Load default settings from the user's configuration file.
if [ -f ~/.eclipse/eclipserc ]; then
    source ~/.eclipse/eclipserc
fi

# If the user has specified a custom JAVA_HOME, we check it for validity.
if [ -n "$JAVA_HOME" ]; then
    echo "using specified JRE: $JAVA_HOME"
    if [ ! -x "$JAVA_HOME"/bin/java ]; then
        echo "The custom VM you have chosen does not have a valid bin/java executable." 1>&2
        exit 1
    fi
fi

# If the user has not set JAVA_HOME, cycle through our list of compatible VM's
# and pick the first one that exists.
if [ -z "$JAVA_HOME" ] && [ -f /etc/eclipse/java_home ]; then
    while read JAVA_HOME; do
        echo -n "  testing $JAVA_HOME..."
        if [ -x "$JAVA_HOME"/bin/java ]; then
            export JAVA_HOME
            break
        fi
    done < <(cat /etc/eclipse/java_home | grep -v '^#' | grep -v '^$')
fi

# If we don't have a JAVA_HOME yet, we're doomed.
if [ -z "$JAVA_HOME" ]; then
    echo "Could not find a suitable JVM." >&2
    exit 1
fi

# Find and verify the existance of the JDT plugin.
JDT_CLASSPATH=$(echo /usr/share/eclipse/plugins/org.eclipse.jdt.core_*.jar)
if [ ! -r "$JDT_CLASSPATH" ]; then
    echo "Could not access the Eclipse JDT." 1>&2
    echo "$JDT_CLASSPATH"
    exit 1
fi


exec $JAVA_HOME/bin/java \
    -classpath $JDT_CLASSPATH \
    org.eclipse.jdt.internal.compiler.batch.Main \
    $@

exit $?
