#!/usr/bin/env bash

# resolve links - $0 may be a softlink
PRG="$0"

while [ -h "$PRG" ] ; do
  ls=`ls -ld "$PRG"`
  link=`expr "$ls" : '.*-> \(.*\)$'`
  if expr "$link" : '/.*' > /dev/null; then
    PRG="$link"
  else
    PRG=`dirname "$PRG"`/"$link"
  fi
done

# Detect the installation directory
INSTALLDIR=`dirname "$PRG"`

if [ -d "$INSTALLDIR/upgrade" ]; then
  if [ -w "$INSTALLDIR" ]; then
    echo Backuping old version ...
    rm -Rf "$INSTALLDIR/old"
    mv "$INSTALLDIR/lib" "$INSTALLDIR/old"
    echo Upgrading ...
    mv -f "$INSTALLDIR/upgrade/boxfuse/lib" "$INSTALLDIR"
    mv -f "$INSTALLDIR/upgrade/boxfuse/"*.txt "$INSTALLDIR"
    rm -Rf "$INSTALLDIR/upgrade"
    echo Upgrade complete.
  else
    echo Upgrade not possible due to missing write permissions. Retry with sudo.
  fi
  echo
fi

if [ -x "$INSTALLDIR/jre/bin/java" ]; then
 JAVA_CMD=$INSTALLDIR/jre/bin/java
else
 # Use JAVA_HOME if it is set
 if [ -z "$JAVA_HOME" ]; then
  JAVA_CMD=java
 else
  JAVA_CMD=$JAVA_HOME/bin/java
 fi
fi


cygwin=false
linux=false
case "`uname`" in
  CYGWIN*|MINGW*) cygwin=true;;
  Linux*) linux=true;;
esac

JAVA_ARGS=
if $linux; then
  JAVA_ARGS=-Djava.security.egd=file:/dev/../dev/urandom
fi

CP="$INSTALLDIR/lib/*"
if $cygwin; then
  CP=$(cygpath -pw "$CP")
fi

if hash $JAVA_CMD 2>/dev/null; then
  "$JAVA_CMD" -Xmx2048m $JAVA_ARGS -cp "$CP" com.boxfuse.client.commandline.Main "$@"
  # Exit using the same code returned from Java
  exit $?
else
  echo ERROR: $JAVA_CMD not found. Make sure it is on the PATH or JAVA_HOME is set.
  exit 1;
fi
