#!/bin/sh

# Use --debug to activate debug mode with an optional argument to specify the port.
# Usage : gecko.sh --debug
#         gecko.sh --debug 9797

# By default debug mode is disabled.
DEBUG_MODE="${DEBUG:-false}"
DEBUG_PORT="${DEBUG_PORT:-8787}"
SERVER_OPTS=""
while [ "$#" -gt 0 ]
do
    case "$1" in
      --debug)
          DEBUG_MODE=true
          if [ -n "$2" ] && [ "$2" = `echo "$2" | sed 's/-//'` ]; then
              DEBUG_PORT=$2
              shift
          fi
          ;;
      -Djava.security.manager*)
          echo "ERROR: The use of -Djava.security.manager has been removed. Please use the -secmgr command line argument or SECMGR=true environment variable."
          exit 1
          ;;
      -secmgr)
          SECMGR="true"
          ;;
      --)
          shift
          break;;
      *)
          SERVER_OPTS="$SERVER_OPTS '$1'"
          ;;
    esac
    shift
done

DIRNAME=`dirname "$0"`
PROGNAME=`basename "$0"`
GREP="grep"

# Use the maximum available, or set MAX_FD != -1 to use that
MAX_FD="maximum"

# OS specific support (must be 'true' or 'false').
cygwin=false;
darwin=false;
linux=false;
solaris=false;
freebsd=false;
other=false
case "`uname`" in
    CYGWIN*)
        cygwin=true
        ;;

    Darwin*)
        darwin=true
        ;;
    FreeBSD)
        freebsd=true
        ;;
    Linux)
        linux=true
        ;;
    SunOS*)
        solaris=true
        ;;
    *)
        other=true
        ;;
esac

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

# Setup GECKO_HOME
RESOLVED_GECKO_HOME=`cd "$DIRNAME/.." >/dev/null; pwd`
if [ "x$GECKO_HOME" = "x" ]; then
    # get the full path (without any relative bits)
    GECKO_HOME=$RESOLVED_GECKO_HOME
else
 SANITIZED_GECKO_HOME=`cd "$GECKO_HOME"; pwd`
 if [ "$RESOLVED_GECKO_HOME" != "$SANITIZED_GECKO_HOME" ]; then
   echo ""
   echo "   WARNING:  GECKO_HOME may be pointing to a different installation - unpredictable results may occur."
   echo ""
   echo "             GECKO_HOME: $GECKO_HOME"
   echo ""
   sleep 2s
 fi
fi
export GECKO_HOME
export GECKO_CONF=$GECKO_HOME/etc

# Read an optional running configuration file
if [ "x$RUN_CONF" = "x" ]; then
    RUN_CONF="$DIRNAME/gecko.conf"
fi
if [ -r "$RUN_CONF" ]; then
    . "$RUN_CONF"
fi

# Set debug settings if not already set
if [ "$DEBUG_MODE" = "true" ]; then
    DEBUG_OPT=`echo $JAVA_OPTS | $GREP "\-agentlib:jdwp"`
    if [ "x$DEBUG_OPT" = "x" ]; then
        JAVA_OPTS="$JAVA_OPTS -agentlib:jdwp=transport=dt_socket,address=$DEBUG_PORT,server=y,suspend=n"
    else
        echo "Debug already enabled in JAVA_OPTS, ignoring --debug argument"
    fi
fi

# Setup the JVM
if [ "x$JAVA" = "x" ]; then
    if [ "x$JAVA_HOME" != "x" ]; then
        JAVA="$JAVA_HOME/bin/java"
    else
        JAVA="java"
    fi
fi

if [ "$PRESERVE_JAVA_OPTS" != "true" ]; then
    # Check for -d32/-d64 in JAVA_OPTS
    JVM_D64_OPTION=`echo $JAVA_OPTS | $GREP "\-d64"`
    JVM_D32_OPTION=`echo $JAVA_OPTS | $GREP "\-d32"`

    # Check If server or client is specified
    SERVER_SET=`echo $JAVA_OPTS | $GREP "\-server"`
    CLIENT_SET=`echo $JAVA_OPTS | $GREP "\-client"`

    if [ "x$JVM_D32_OPTION" != "x" ]; then
        JVM_OPTVERSION="-d32"
    elif [ "x$JVM_D64_OPTION" != "x" ]; then
        JVM_OPTVERSION="-d64"
    elif $darwin && [ "x$SERVER_SET" = "x" ]; then
        # Use 32-bit on Mac, unless server has been specified or the user opts are incompatible
        "$JAVA" -d32 $JAVA_OPTS -version > /dev/null 2>&1 && PREPEND_JAVA_OPTS="-d32" && JVM_OPTVERSION="-d32"
    fi

    if [ "x$CLIENT_SET" = "x" -a "x$SERVER_SET" = "x" ]; then
        # neither -client nor -server is specified
        if $darwin && [ "$JVM_OPTVERSION" = "-d32" ]; then
            # Prefer client for Macs, since they are primarily used for development
            PREPEND_JAVA_OPTS="$PREPEND_JAVA_OPTS -client"
        else
            PREPEND_JAVA_OPTS="$PREPEND_JAVA_OPTS -server"
        fi
    fi

    JAVA_OPTS="$PREPEND_JAVA_OPTS $JAVA_OPTS"
fi


if $linux; then
    # consolidate the server and command line opts
    CONSOLIDATED_OPTS="$JAVA_OPTS $SERVER_OPTS"
    # process the standalone options
    for var in $CONSOLIDATED_OPTS
    do
       # Remove quotes
       p=`echo $var | tr -d "'"`
       case $p in
         -Dgecko.base.dir=*)
              GECKO_BASE_DIR=`readlink -m ${p#*=}`
              ;;
         -Dgecko.data.dir=*)
              GECKO_DATA_DIR=`readlink -m ${p#*=}`
              ;;
         -Dgecko.log.dir=*)
              GECKO_LOG_DIR=`readlink -m ${p#*=}`
              ;;
         -Dgecko.config.dir=*)
              GECKO_CONFIG_DIR=`readlink -m ${p#*=}`
              ;;
       esac
    done
fi

if $solaris; then
    # consolidate the server and command line opts
    CONSOLIDATED_OPTS="$JAVA_OPTS $SERVER_OPTS"
    # process the standalone options
    for var in $CONSOLIDATED_OPTS
    do
       # Remove quotes
       p=`echo $var | tr -d "'"`
      case $p in
        -Dgecko.base.dir=*)
             GECKO_BASE_DIR=`echo $p | awk -F= '{print $2}'`
             ;;
        -Dgecko.data.dir=*)
             GECKO_DATA_DIR=`echo $p | awk -F= '{print $2}'`
             ;;
        -Dgecko.log.dir=*)
             GECKO_LOG_DIR=`echo $p | awk -F= '{print $2}'`
             ;;
        -Dgecko.config.dir=*)
             GECKO_CONFIG_DIR=`echo $p | awk -F= '{print $2}'`
             ;;
      esac
    done
fi

# No readlink -m on BSD
if $darwin || $freebsd || $other ; then
    # consolidate the server and command line opts
    CONSOLIDATED_OPTS="$JAVA_OPTS $SERVER_OPTS"
    # process the standalone options
    for var in $CONSOLIDATED_OPTS
    do
       # Remove quotes
       p=`echo $var | tr -d "'"`
       case $p in
         -Dgecko.base.dir=*)
              GECKO_BASE_DIR=`cd ${p#*=} ; pwd -P`
              ;;
         -Dgecko.data.dir=*)
              GECKO_DATA_DIR=`cd ${p#*=} ; pwd -P`
              ;;
         -Dgecko.log.dir=*)
              if [ -d "${p#*=}" ]; then
                GECKO_LOG_DIR=`cd ${p#*=} ; pwd -P`
             else
                #since the specified directory doesn't exist we don't validate it
                GECKO_LOG_DIR=${p#*=}
             fi
             ;;
         -Dgecko.config.dir=*)
              GECKO_CONFIG_DIR=`cd ${p#*=} ; pwd -P`
              ;;
       esac
    done
fi

# determine the default base dir, if not set
if [ "x$GECKO_BASE_DIR" = "x" ]; then
   GECKO_BASE_DIR="$GECKO_HOME"
fi

# determine the default base dir, if not set
if [ "x$GECKO_DATA_DIR" = "x" ]; then
   GECKO_DATA_DIR="$GECKO_BASE_DIR/data"
fi

# determine the default log dir, if not set
if [ "x$GECKO_LOG_DIR" = "x" ]; then
   GECKO_LOG_DIR="$GECKO_BASE_DIR/logs"
fi
# determine the default configuration dir, if not set
if [ "x$GECKO_CONFIG_DIR" = "x" ]; then
   GECKO_CONFIG_DIR="$GECKO_BASE_DIR/etc"
fi

# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
    GECKO_HOME=`cygpath --path --windows "$GECKO_HOME"`
    JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
    GECKO_BASE_DIR=`cygpath --path --windows "$GECKO_BASE_DIR"`
    GECKO_DATA_DIR=`cygpath --path --windows "$GECKO_DATA_DIR"`
    GECKO_LOG_DIR=`cygpath --path --windows "$GECKO_LOG_DIR"`
    GECKO_CONFIG_DIR=`cygpath --path --windows "$GECKO_CONFIG_DIR"`
fi

# Process the JAVA_OPTS and fail the script of a java.security.manager was found
SECURITY_MANAGER_SET=`echo $JAVA_OPTS | $GREP "java\.security\.manager"`
if [ "x$SECURITY_MANAGER_SET" != "x" ]; then
    echo "ERROR: The use of -Djava.security.manager has been removed. Please use the -secmgr command line argument or SECMGR=true environment variable."
    exit 1
fi

# Display our environment
echo "========================================================================="
echo ""
echo "  Gecko Bootstrap Environment"
echo ""
echo "  JAVA: $JAVA"
echo ""
echo "  JAVA_OPTS: $JAVA_OPTS"
echo ""
echo "========================================================================="
echo ""

while true; do
   if [ "x$LAUNCH_GECKO_IN_BACKGROUND" = "x" ]; then
      # Execute the JVM in the foreground
      eval \"$JAVA\" $JAVA_OPTS \
         \"-Dlogback.configurationFile=$GECKO_HOME/$GECKO_LOG_CONFIG_FILE\" \
         \"-DGECKO_LOG_DIR=$GECKO_LOG_DIR\" \
         -Dorg.osgi.service.http.port=-1 \
         -Dgosh.args=--nointeractive \
         -Dgecko.base.dir=\""$GECKO_BASE_DIR"\" \
         -Dgecko.conf.dir=\""$GECKO_CONFIG_DIR"\" \
         -Dgecko.data.dir=\""$GECKO_DATA_DIR"\" \
         -jar \"$GECKO_HOME/lib/launch.jar\" \
      GECKO_STATUS=$?
   else
      # Execute the JVM in the background
      eval \"$JAVA\" $JAVA_OPTS \
         \"-Dlogback.configurationFile=$GECKO_HOME/$GECKO_LOG_CONFIG_FILE\" \
         \"-DGECKO_LOG_DIR=$GECKO_LOG_DIR\" \
         -Dorg.osgi.service.http.port=-1 \
         -Dgosh.args=--nointeractive \
         -Dgecko.base.dir=\""$GECKO_BASE_DIR"\" \
         -Dgecko.conf.dir=\""$GECKO_CONFIG_DIR"\" \
         -Dgecko.data.dir=\""$GECKO_DATA_DIR"\" \
         -jar \"$GECKO_HOME/lib/launch.jar\" \
         "&"
      GECKO_PID=$!
      # Trap common signals and relay them to the gecko process
      trap "kill -HUP  $GECKO_PID" HUP
      trap "kill -TERM $GECKO_PID" INT
      trap "kill -QUIT $GECKO_PID" QUIT
      trap "kill -PIPE $GECKO_PID" PIPE
      trap "kill -TERM $GECKO_PID" TERM
      if [ "x$GECKO_PIDFILE" != "x" ]; then
        echo $GECKO_PID > $GECKO_PIDFILE
      fi
      # Wait until the background process exits
      WAIT_STATUS=128
      while [ "$WAIT_STATUS" -ge 128 ]; do
         wait $GECKO_PID 2>/dev/null
         WAIT_STATUS=$?
         if [ "$WAIT_STATUS" -gt 128 ]; then
            SIGNAL=`expr $WAIT_STATUS - 128`
            SIGNAL_NAME=`kill -l $SIGNAL`
            echo "*** Gecko Server process ($GECKO_PID) received $SIGNAL_NAME signal ***" >&2
         fi
      done
      if [ "$WAIT_STATUS" -lt 127 ]; then
         GECKO_STATUS=$WAIT_STATUS
      else
         GECKO_STATUS=0
      fi
      if [ "$GECKO_STATUS" -ne 10 ]; then
            # Wait for a complete shutdown
            wait $GECKO_PID 2>/dev/null
      fi
      if [ "x$GECKO_PIDFILE" != "x" ]; then
            grep "$GECKO_PID" $GECKO_PIDFILE && rm $GECKO_PIDFILE
      fi
   fi
   if [ "$GECKO_STATUS" -eq 10 ]; then
      echo "Restarting Gecko runtime ..."
   else
      exit $GECKO_STATUS
   fi
done