#!/bin/sh
# Simple wrapper script used to start mkgmapgui in Debian
set -e

# First, the alternative (if known to work) or users preference as defined by $JAVA_HOME. Next, use OpenJDK or Sun's proprietary JDK.
# Override to a specific one using $JAVACMD
ALTERNATIVE_JDK="`readlink -n -f /etc/alternatives/java`"

# Let's get the current architecture -- needed for multiarchified Java
ARCH="`dpkg --print-architecture`"

# If OpenJDK is only available headless, do not try it
if dpkg --get-selections 'openjdk-*-jre' | grep install$ > /dev/null ; then
   JAVA_CMDS="$JAVA_HOME/bin/java"
   JAVA_CMDS="${JAVA_CMDS} /usr/lib/jvm/java-8-openjdk-$ARCH/bin/java"
   JAVA_CMDS="${JAVA_CMDS} /usr/lib/jvm/java-7-openjdk-$ARCH/bin/java"
   JAVA_CMDS="${JAVA_CMDS} /usr/lib/jvm/java-6-openjdk/bin/java /usr/lib/jvm/java-6-openjdk-$ARCH/bin/java /usr/lib/jvm/java-6-sun/bin/java"
else
   JAVA_CMDS="$JAVA_HOME/bin/java"
   JAVA_CMDS="${JAVA_CMDS} /usr/lib/jvm/java-6-sun/bin/java"
fi

if [ -z "$JAVA_OPTS" -o $(echo "$JAVA_OPTS" | grep "\-Xmx" | wc -l) -eq 0 ]; then
    JAVA_OPTS="$JAVA_OPTS -Xmx512M"
fi

if [ -z "${JAVACMD}" ]; then
    for jcmd in $JAVA_CMDS; do
       if [ "z$ALTERNATIVE_JDK" = "z`readlink -n -f $jcmd`" ] && [ -z "${JAVACMD}" ]; then
          JAVACMD="$jcmd"
          break
       fi
    done
fi

if [ -z "${JAVACMD}" ]; then
    for jcmd in $JAVA_CMDS; do
       if [ -x "$jcmd" -a -z "${JAVACMD}" ]; then
          JAVACMD="$jcmd"
          break
       fi
    done
fi

if [ "$JAVACMD" ]; then
   echo "Using $JAVACMD to execute mkgmapgui."
   exec $JAVACMD $JAVA_OPTS -jar /usr/share/mkgmapgui/mkgmapgui.jar /usr/share/mkgmap/mkgmap.jar
else
   echo "No valid JVM found to run mkgmapgui."
   exit 1
fi
