#!/bin/sh

# Default to running in the background
fg_default=0

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

export _BEAGLED_INDEX_HELPER_PATH="/usr/lib/beagle"
export MONO_PATH="/usr/lib/beagle${MONO_PATH+:$MONO_PATH}"
export LD_LIBRARY_PATH="/usr/lib/beagle${LD_LIBRARY_PATH+:$LD_LIBRARY_PATH}"

# 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+:$MONO_GAC_PREFIX}"
export LD_LIBRARY_PATH="/opt/gnome/lib/evolution/2.0${LD_LIBRARY_PATH+:$LD_LIBRARY_PATH}"
monogrind=0
heap_buddy=0

BEAGLED_ARGS="$*"
for i in $BEAGLED_ARGS; do
    case "$i" in
    --help | --list-backends | --fg | --foreground ) fg_user=1 ;;
    --bg | --background ) fg_user=0 ;;
    --monogrind ) monogrind=1 ;;
    --heap-buddy ) heap_buddy=1 ;;
    esac
done

# If the user didn't specify to run in fg/bg, then use the default
if [ -z "$fg_user" ]; then
    fg=$fg_default
else
    fg=$fg_user
fi

# Handle logging, and optionally append the relevent default fg/bg argument if
# it was not user-specified.
if [ $fg -eq 1 ]; then
    [ -z "$fg_user" ] && FGBG_ARG="--fg";
    export BEAGLE_LOG_IN_THE_FOREGROUND_PLEASE=1
else
    [ -z "$fg_user" ] && FGBG_ARG="--bg";
    unset BEAGLE_LOG_IN_THE_FOREGROUND_PLEASE
fi

if [ $heap_buddy -eq 1 ]; then
   export _GET_ON_THE_HEAP_BUDDY_BANDWAGON=1
   MONO_EXTRA_ARGS="--profile=heap-buddy:outfile.beagled $MONO_EXTRA_ARGS"
   rm -f outfile.beagled outfile.helper.*
fi

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

PROCESS_NAME="mono-beagled"

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

# If beagled (in --bg mode) has exited with some errors, we need 
# to inform the users about the same. This 500 milli-seconds sleep
# is to wait for the daemon to start and exit, in case of errors ;)
# Fixes http://bugzilla.gnome.org/show_bug.cgi?id=171975

sleep 0.5

if ! ps -p $! > /dev/null; then
    echo "Beagle Daemon exited with errors.  See ~/.beagle/Log/current-Beagle for more details."
fi
