#!/bin/bash

# DEBUG=1
FLEXIBEE_SERVER_ARGS=""
FLEXIBEE_ARGS=""
FLEXIBEE_JAVA_ARGS="-Xmx1g -client -XX:-OmitStackTraceInFastThrow"
FLEXIBEE_LIB_DIR="/usr/share/flexibee/lib/"
FLEXIBEE_CACHE_DIR="$HOME/.winstrom/cache/"

if [ -f /usr/share/flexibee/bin/functions ]; then
    . /usr/share/flexibee/bin/functions
fi

# Fix for Stupid Debian settings in /etc/sysctl.d/bindipv6only.conf
if [ -f /proc/sys/net/ipv6/bindv6only -a x"`cat /proc/sys/net/ipv6/bindv6only`" = x"1" ]; then
    FLEXIBEE_JAVA_ARGS="${FLEXIBEE_JAVA_ARGS} -Djava.net.preferIPv4Stack=true"
    echo "Disabling IPv6 support in ABRA Flexi due to the System settings"
fi

if [ -f /etc/default/flexibee ]; then
	. /etc/default/flexibee
fi

findjava
if [ $? -ne 0 ]
then
	exit 1
fi

winstrompath=$(dirname "$0")
cd $winstrompath;		    # we need to resolve relative paths
winstrompath=$(pwd)
winstrompath="${winstrompath%/bin}" # nothing happens if winstrom is not installed
	                            # under something/bin


# we try different possibilities to find winstrom jars
for jar in "${winstrompath}" "${winstrompath}/share/flexibee" "${winstrompath}/flexibee" "${winstrompath}/share/winstrom" "${winstrompath}/winstrom"
do
	for i in ${jar}/lib/winstrom-*.jar; do
		if [ -f $i ]; then
			winstromdir="${jar}"
			_debug "ABRA Flexi Directory is '${jar}'."
			break
		fi
	done

	if [ ! -z "${winstromdir}" ]; then
		break
	fi
done

if [ -z "${winstromdir}" ]
then
	_error "Couldn't find flexibee under '${winstrompath}'."
	exit 1
fi

_debug "ABRA Flexi Directory is '${winstromdir}'."

# The CLASSPATH also lets one specify additional jars, which is good, if
# you want to add a new Look&Feel jar (the motif one is so ugly...).

export CLASSPATH="${ADD_JARS}:${CLASSPATH}"
for i in ${winstromdir}/lib/classworlds*.jar; do
	CLASSPATH="${i}:${CLASSPATH}"
done

_debug "ClassPath is '$CLASSPATH'."

# Go back to user's home for default directory in backups, ...
cd $HOME

# Support for server as part of client.
# if [ x"$FLEXIBEE_CFG" = x"local" ]; then
#    FLEXIBEE_SERVER_ARGS="-c /etc/flexibee/flexibee-server.xml $FLEXIBEE_SERVER_ARGS"
# fi

${JAVACMD} -cp $CLASSPATH -Dwinstromdir=${winstromdir}/lib -splash:${winstromdir}/winstrom-splash.png -Dclassworlds.conf=${winstromdir}/lib/launcher.txt  $FLEXIBEE_JAVA_ARGS org.codehaus.classworlds.Launcher $FLEXIBEE_ARGS $@
