#!/bin/bash
#
# fanlaunch: common code for unix scripts
#

# Operating system
cygwin=false;
darwin=false;
linux=false;
case "`uname`" in
    CYGWIN*)
      cygwin=true
      ;;
    Darwin*)
      darwin=true
      ;;
    Linux*)
      linux=true
      ;;
esac

# MAC OS X we have to set to set a special flag
# to ensure that SWT will run correctly
if $darwin; then
  osFlags="-XstartOnFirstThread"
fi

# Set FAN_HOME if it is not already set (from Groovy)
if [ -z "$FAN_HOME" -o ! -d "$FAN_HOME" ] ; then
  # Resolve links: $0 may be a link
  PRG="$0"
  # Need this for relative symlinks.
  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
  SAVED="`pwd`"
  cd "`dirname \"$PRG\"`/.."
  FAN_HOME="`pwd -P`"
  cd "$SAVED"
fi

# Set FAN_CP classpath if not already set
if [ -z "$FAN_CP" -o ! -d "$FAN_CP" ] ; then
  # always put sys.jar and jline.jar in classpath
  FAN_CP="$FAN_HOME/lib/java/sys.jar:$FAN_HOME/lib/java/jline.jar"
fi

# Set FAN_JAVA if not already set
if [ -z "$FAN_JAVA" ] ; then
  if [ ! -z "$JAVA_HOME" ]; then
    FAN_JAVA="$JAVA_HOME/bin/java"
  else
    FAN_JAVA=`which java`
  fi
  if [ ! -x "$FAN_JAVA" ] ; then
    echo "Cannot find java, please either add the java bin directory to"
    echo "the PATH environment variable or set the FAN_JAVA variable to"
    echo "the path of the java binary file"
    exit 1
  fi
fi

FAN_CONFIG_PROPS="$FAN_HOME/etc/sys/config.props"
FAN_CLASSPATH="$FAN_CP":"$CLASSPATH"

# On Cygwin, convert paths to Windows-style (as expected by a JVM running on Windows)
if $cygwin; then
  FAN_HOME=`cygpath --windows $FAN_HOME`
  FAN_CLASSPATH=`cygpath --windows --path $FAN_CLASSPATH`
  if [ ! -z "$JAVA_HOME" ] ; then
    JAVA_HOME=`cygpath --windows $JAVA_HOME`
  fi
fi

# read a single line property from props file
read_prop()
{
  eval "$1='`sed '/^\#/d' "$2" | sed '/^\/\//d' | grep \"$3=\"  | tail -n 1 | sed 's/^[^=]*=//;s/^[[:space:]]*//;s/[[:space:]]*$//'`'"
}
# Launcher function
fanlaunch()
{
  FAN_MAIN="fanx.tools.$1"
  shift
  read_prop JAVA_OPTIONS "$FAN_CONFIG_PROPS" java.options
  exec "$FAN_JAVA" $osFlags $JAVA_OPTIONS $libPath -cp "$FAN_CLASSPATH" -Dfan.home="$FAN_HOME" "$FAN_MAIN" "$@"
}
