#!/bin/sh

if [ -e ./BeagleDaemon.exe ] && [ -e ./Makefile.am ] ; then
    echo "Running uninstalled BeagleDaemon.exe."

    # When we run uninstalled, run in the foreground by default.
    fg_default=1

    TARGET_EXE="./BeagleDaemon.exe"
    EXTRA_ARGS=""

    export _BEAGLED_INDEX_HELPER_PATH="."
    export MONO_PATH="../Util:../BeagleClient:$MONO_PATH"
    export LD_LIBRARY_PATH="../glue/.libs:$LD_LIBRARY_PATH"

    # In BEAGLE_FILTER_PATH, a trailing ':' means "append the default path".
    if [ -n "$BEAGLE_FILTER_PATH" ]; then
	export BEAGLE_FILTER_PATH="../Filters:$BEAGLE_FILTER_PATH"
    else
	export BEAGLE_FILTER_PATH="../Filters"
    fi
else

    # Otherwise default to running in the background
    fg_default=0

    TARGET_EXE="/usr/lib64/beagle/BeagleDaemon.exe"
    EXTRA_ARGS=""

    export _BEAGLED_INDEX_HELPER_PATH="/usr/lib64/beagle"
    export MONO_PATH="/usr/lib64/beagle:$MONO_PATH"
    export LD_LIBRARY_PATH="/usr/lib64/beagle:$LD_LIBRARY_PATH"
fi

# This disables mono's emulation of the win32 file locking semantics,
# which speeds up lucene.
#
# ... but they also make things pretty unstable on Mono 1.1.x,
# including calling out to processes non-functional.
#export MONO_DISABLE_SHM=1

export MONO_GAC_PREFIX="/usr:$MONO_GAC_PREFIX"
export LD_LIBRARY_PATH="/opt/gnome/lib/evolution/2.0:$LD_LIBRARY_PATH"


# Do any necessary processing of the arguments,
# filtering out ones that are only used by this script

fg=$fg_default
need_fgbg_arg=1
monogrind=0

declare -a args
while [ $# -gt 0 ]; do
    case "$1" in
	--fg | --foreground ) fg=1 ; shift ;;
	--bg | --background ) fg=0 ; shift ;;
	--monogrind ) monogrind=1; shift ;;
	*) args[${#args[@]}]=$1 ; shift ;;
    esac
done


# Append a --fg or --bg at the end of the command line so that
# the daemon can know whether or not it is running in the background.
FGBG_ARG=""
if [ $fg -eq 1 ]; then
    FGBG_ARG="--fg";
    export BEAGLE_LOG_IN_THE_FOREGROUND_PLEASE=1
else
    FGBG_ARG="--bg";
    unset BEAGLE_LOG_IN_THE_FOREGROUND_PLEASE
fi

if [ $monogrind -eq 1 ]; then
    export GC_DONT_GC=1
    CMDLINE="monogrind $TARGET_EXE $EXTRA_ARGS ${args[@]} $FGBG_ARG"
else
    CMDLINE="mono --debug $MONO_EXTRA_ARGS $TARGET_EXE $EXTRA_ARGS ${args[@]} $FGBG_ARG"
fi

PROCESS_NAME="mono-beagled"

if [ $fg -eq 1 ]; then
    exec -a $PROCESS_NAME $CMDLINE
else
    exec -a $PROCESS_NAME $CMDLINE &
fi
