#!/bin/sh -e

#
# guess path of this program
#
get_real_own_dirname()
{
	own_filename=`basename $0`
	own_dirname=`dirname $0`

	if ! (echo "${own_dirname}" | grep '^/' >/dev/null); then
		if [ -x "${own_dirname}/${own_filename}" ]; then
			own_dirname=`cd ${own_dirname} && pwd`
		else
			for dir in `echo "${PATH}" | sed 's/:/ /g'`
			do
				if [ -x "${dir}/${own_filename}" ]; then
					own_dirname="${dir}"
					break
				fi
			done
		fi
	fi

	if [ -L "${own_dirname}/${own_filename}" ]; then
		dirname `readlink "${own_dirname}/${own_filename}"`
	else
		printf '%s' "${own_dirname}"
	fi
}


#
# change directory
#
cd `get_real_own_dirname`


#
# set memory quantity to use
#
memory='' # system default

case "`uname`" in
	FreeBSD|Darwin)
		memory=`sysctl -n hw.usermem \
			|awk '{printf("%d", $0 / 1024 / 1024 * 0.85)}'`
		if [ $memory -gt 1536 ]; then
			memory=1536
		elif [ $memory -lt 64 ]; then
			memory=''
		fi
		;;

	Linux)
		;;

	*)
		;;
esac

memory_option=''
if [ X"${memory}" != X'' ]; then
	memory_option="-Xmx${memory}m"
fi


#
# execute
#
exec java -server -ea ${memory_option} -Dfile.encoding=utf-8 \
	  -jar daruma.jar ${1+"$@"}
