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

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=$(( ${totalmem} * 1024 ))
  usrdir=/usr
elif [ "${PLATFORM}" = "FreeBSD" ]; then
  totalmem=`sysctl -n hw.physmem`
  totalmem=$(( ${totalmem} / 1024 ))
  usrdir=%%LOCALBASE%%
fi

if [ -d ${usrdir}/share/java/lightzone ]; then
  pkgjavadir=${usrdir}/share/java/lightzone
else
  # Gentoo
  pkgjavadir=${usrdir}/share/lightzone/lib
fi

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

classpath=${pkgjavadir}'/*'
if   [ -d ${usrdir}/share/java ]; then  # Debian, Ubuntu, Fedora, OpenSUSE, PCLinuxOS
   classpath=${classpath}:${usrdir}/share/java/'*'
fi
if [ -d ${usrdir}/share/java/classes ]; then  # FreeBSD
   classpath=${classpath}:${usrdir}/share/java/classes/'*'
fi
for name in javahelp; do  # TODO: Add paths for other jars
  if [ -d ${usrdir}/share/java/${name} ]; then  # Arch
     classpath=${classpath}:${usrdir}/share/java/${name}/'*'
  elif [ -d ${usrdir}/share/${name}/lib ]; then  # Gentoo
     classpath=${classpath}:${usrdir}/share/${name}/lib/'*'
  elif [ -d ${usrdir}/j2se/opt/${name}/lib ]; then  # OpenIndiana
     classpath=${classpath}:${usrdir}/j2se/opt/${name}/lib/'*'
  fi
done

minmem=524288
maxmem=${minmem}

javapref=${HOME}/.java/.userPrefs/com/lightcrafts/app/prefs.xml
if [ -f ${javapref} ]; then
  maxmem_pref=`xmllint --xpath 'map/entry[@key="MaxMemory"]/@value' ${javapref} | sed -r 's/value=\"([0-9]+)\"/\1/'`
  if [ ! -z ${maxmem_pref} ]; then
    maxmem=$(( ${maxmem_pref} * 1024 ))
  fi
fi

if [ ${maxmem} -le ${minmem} ]; then
  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=${minmem}
  fi
fi

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

echo ${classpath}
(cd ${pkgjavadir} && LD_LIBRARY_PATH=${pkglibexecdir} exec java \
-classpath ${classpath} \
-XX:+UseG1GC \
-XX:MinHeapFreeRatio=30 \
-XX:MaxHeapFreeRatio=30 \
-Xmx${maxmem}k \
-Djava.library.path=${pkglibexecdir} \
-Dfile.encoding=UTF8 \
com.lightcrafts.platform.linux.LinuxLauncher ${file} ${@} )
