#! /bin/bash
set -e

# Locate the script file.  Cross symlinks if necessary.
loc="$0"
while [ -h "$loc" ]; do
    ls=`ls -ld "$loc"`
    link=`expr "$ls" : '.*-> \(.*\)$'`
    if expr "$link" : '/.*' > /dev/null; then
        loc="$link"  # Absolute link
    else
        loc="`dirname "$loc"`/$link"  # Relative link
    fi
done
base_dir=$(cd `dirname "$loc"` && pwd)

# Just the first two digits of the version.
java_version=$(java -version 2>&1 | sed -ne '1s/.*"\([0-9][0-9]*\.[0-9][0-9]*\)\..*/\1/p')

if [[ "$java_version" == 1.[0-5] ]]; then
    echo "Executing \"java -version\" reports \"$java_version\"." 1>&2
    echo "We require at least Java 1.6." 1>&2
    exit 1
fi

jvm_args=()
if [[ "$java_version" == 1.[6-7] ]]; then
    jvm_args+=(-XX:MaxPermSize=256M)  # Not relevant to JDK 1.8+
fi

java \
    -Xms512M -Xmx1024M -Xss1M -XX:+CMSClassUnloadingEnabled "${jvm_args[@]}" \
    -Djava.security.manager -Djava.security.policy="$base_dir/sbt.security.policy" \
    -jar "$base_dir/sbt-launch.jar" \
    -Dsbt.override.build.repos=true \
    -Dsbt.repository.config="$base_dir/sbt.resolvers.properties" \
    "$@"
