#! /bin/sh

# OS specific support.  $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
case "`uname`" in
  CYGWIN*) 
    cygwin=true 
    ;;
  Darwin*) 
    darwin=true
    [ -z "$JAVA_HOME" ] && {
      export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Home   
    }
    ;;
esac

[ -z "$JAVA_HOME" ] && echo "Please set the JAVA_HOME environment variable." && exit 1

[ -z "$FIRESTORM_HOME" ] && {
  # try to find FireStorm
  if [ -d /opt/firestorm-2.0 ] ; then 
    FIRESTORM_HOME=/opt/firestorm-2.0
  elif [ -d "${HOME}/opt/firestorm-2.0" ] ; then 
    FIRESTORM_HOME="${HOME}/opt/firestorm-2.0"
  else
    ## resolve links - $0 may be a link to FireStorm's home
    PRG="$0"
    progname="`basename \"$0\"`"
    saveddir=`pwd`

    # need this for relative symlinks
    cd "`dirname \"$PRG\"`"
  
    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
  
    FIRESTORM_HOME="`dirname \"$PRG\"`/.."

    cd "$saveddir"

    # make it fully qualified
    FIRESTORM_HOME="`cd \"$FIRESTORM_HOME\" && pwd`"
  fi
}

# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
  FIRESTORM_HOME="`cygpath --unix \"$FIRESTORM_HOME\"`"
  JAVA_HOME="`cygpath --unix \"$JAVA_HOME\"`"
  [ -n "$CLASSPATH" ] && CLASSPATH="`cygpath --path --unix \"$CLASSPATH\"`"
fi

[ -z "$JAVACMD" ] && {
    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 
      # IBM's JDK on AIX uses strange locations for the executables
      JAVACMD="$JAVA_HOME/jre/sh/java"
    else
      JAVACMD="$JAVA_HOME/bin/java"
    fi
}
 
if [ ! -x "$JAVACMD" ] ; then
  echo "Error: JAVA_HOME is not defined correctly."
  echo "  Cannot execute $JAVACMD"
  exit 1
fi

[ -n "$CLASSPATH" ] && LOCALCLASSPATH="$CLASSPATH"

[ -f "$JAVA_HOME/lib/tools.jar" ] && \
    LOCALCLASSPATH="$LOCALCLASSPATH:$JAVA_HOME/lib/tools.jar"

[ -f "$JAVA_HOME/lib/classes.zip" ] && \
    LOCALCLASSPATH="$LOCALCLASSPATH:$JAVA_HOME/lib/classes.zip"

EXTRA_OPTS=

# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
  FIRESTORM_HOME="`cygpath --path --windows \"$FIRESTORM_HOME\"`"
  JAVA_HOME="`cygpath --path --windows \"$JAVA_HOME\"`"
  [-n "$CLASSPATH" ] && CLASSPATH="`cygpath --path --windows \"$CLASSPATH\"`"
  LOCALCLASSPATH="`cygpath --path --windows \"$LOCALCLASSPATH\"`"
  CYGHOME="`cygpath --path --windows \"$HOME\"`"
  EXTRA_OPTS="-Dcygwin.user.home=\"$CYGHOME\""
fi

"$JAVACMD" \
    -classpath $LOCALCLASSPATH \
    -Dfirestorm.home=$FIRESTORM_HOME \
    $EXTRA_OPTS \
    -jar $FIRESTORM_HOME/lib/firestorm.jar \
    $FIRESTORM_ARGS "$@"

