#!/bin/sh
#
# LightZone startscript
#
echo Starting LightZone version 4.1.2 ...
echo with options : ${@}

arch=`getconf LONG_BIT`
PLATFORM=`uname`
if [ "${PLATFORM}" = "Linux" ]; then
  totalmem=`cat /proc/meminfo | grep 'MemTotal: ' | sed -r 's/.* ([0-9]+) .*/\1/'`
  usrdir=/usr
elif [ "${PLATFORM}" = "SunOS" ]; then
  totalmem=`prtconf | grep 'Memory size:' | sed -r 's/.* ([0-9]+) .*/\1/'`
  totalmem=`expr $totalmem \* 1024`
  usrdir=/usr
elif [ "${PLATFORM}" = "FreeBSD" ]; then
  totalmem=`dmesg | grep 'real memory' | sed -r 's/.* ([0-9]+) .*/\1/'`
  totalmem=`expr $totalmem / 1024`
  usrdir=/usr/local
fi

pkgjavadir=${usrdir}/share/java/lightzone
if [ -d ${usrdir}/libexec/lightzone ]; then
  pkglibexecdir=${usrdir}/libexec/lightzone
elif [ -d ${usrdir}/lib64/lightzone ]; then
  pkglibexecdir=${usrdir}/lib64/lightzone
else
  pkglibexecdir=${usrdir}/lib/lightzone
fi

classdir='/usr/share/java/javahelp/*:/usr/share/java/*:/usr/share/javahelp/lib/*:/usr/local/share/java/classes/*'

if [ $totalmem -ge 1048576 ]; then
  maxmem=$(( $totalmem / 2 ))
  # on 32-bit architectures there is ~2GB limit for maximum Java heap size
  if [ $arch = "32" -a $totalmem -ge 4194304 ]; then
    maxmem=2097152
  fi
else
    maxmem=524288
fi

# IFS should be \n to handle filenames that include space.
IFS="
"
file=""
for i in "$@"; do
  if [ -f $i ] ; then
    file=$(cd $(dirname $i) && pwd)/$(basename $i)
    break
  fi
done

(cd $pkgjavadir && LD_LIBRARY_PATH=$pkglibexecdir exec java -Xmx${maxmem}k -Djava.library.path=$pkglibexecdir -Dfile.encoding=UTF8 -classpath "$pkgjavadir/*:$classdir" com.lightcrafts.platform.linux.LinuxLauncher ${file} ${@} )
