#!/bin/sh

if test "x$GTK_DEBUG_LAUNCHER" != x; then
    set -x
fi

if test "x$GTK_DEBUG_GDB" != x; then
    EXEC="gdb --args"
else
    EXEC=exec
fi

name=`basename "$0"`
tmp="$0"
tmp=`dirname "$tmp"`
tmp=`dirname "$tmp"`
bundle=`dirname "$tmp"`
bundle_contents="$bundle"/Contents
bundle_res="$bundle_contents"/Resources
bundle_fw="$bundle_contents"/Frameworks
bundle_lib="$bundle_res"/lib
bundle_bin="$bundle_res"/bin
bundle_data="$bundle_res"/share
bundle_etc="$bundle_res"/etc

export DYLD_LIBRARY_PATH="$bundle_lib"
export XDG_CONFIG_DIRS="$bundle_etc"/xdg
export XDG_DATA_DIRS="$bundle_data"
export GTK_DATA_PREFIX="$bundle_res"
export GTK_EXE_PREFIX="$bundle_res"
export GTK_PATH="$bundle_res"

export GTK2_RC_FILES="$bundle_etc/gtk-2.0/gtkrc"
if [ `uname -r | cut -d . -f 1` -ge 10 ]; then
    export GTK_IM_MODULE_FILE="$bundle_etc/gtk-2.0/gtk.immodules"
fi
export GDK_PIXBUF_MODULE_FILE="$bundle_lib/gdk-pixbuf-2.0/2.10.0/loaders.cache"
export PANGO_RC_FILE="$bundle_etc/pango/pangorc"
export PANGO_SYSCONFDIR="$bundle_etc"
export PANGO_LIBDIR="$bundle_lib"

if test -f "$bundle_lib/charset.alias"; then
    export CHARSETALIASDIR="$bundle_lib"
fi

# Extra arguments can be added in environment.sh.
EXTRA_ARGS=" --debug"

if test -f "$bundle_res/environment.sh"; then
  source "$bundle_res/environment.sh"
fi

# Strip out the argument added by the OS.
if /bin/expr "x$1" : "x-psn_.*" > /dev/null; then
    shift 1
fi

export RESPFX="${bundle_res}"
PATH="${RESPFX}"/bin:/bin:/usr/bin
export PATH

GUILE_WARN_DEPRECATED="no"
export GUILE_WARN_DEPRECATED


GNC_MODULE_PATH="${RESPFX}/lib/gnucash:${GNC_MODULE_PATH}"

GUILE_LIBS="${bundle_data}/guile/2.0/"
GUILE_COMPILED_LIBS="${bundle_lib}/guile/2.0/ccache"

EXTRA_LIBS="${GNC_MODULE_PATH}"
EXTRA_LIBS="${EXTRA_LIBS}:/System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/ImageIO.framework/Versions/A/Resources/"
EXTRA_LIBS="${EXTRA_LIBS}:${RESPFX}/lib"
EXTRA_LIBS="${EXTRA_LIBS}:${RESPFX}/lib/gnucash"

LD_LIBRARY_PATH="${LD_LIBRARY_PATH}:${EXTRA_LIBS}:"
DYLD_LIBRARY_PATH="${DYLD_LIBRARY_PATH}:${EXTRA_LIBS}"
export DYLD_FRAMEWORK_PATH="${bundle_fw}"
export GNC_STANDARD_REPORTS_DIR="${bundle_data}/gnucash/scm/gnucash/report/standard-reports"
export GSETTINGS_SCHEMA_DIR="${bundle_data}"

export GNC_MODULE_PATH
export GUILE_LIBS
export GUILE_COMPILED_LIBS
export LD_LIBRARY_PATH
export DYLD_LIBRARY_PATH
export GNC_DOT_DIR="$HOME/Library/Application Support/Gnucash"
export OFX_DTD_PATH="${bundle_data}/libofx/dtd"

if test -f "$GNC_DOT_DIR/gnucashrc"; then
    source "$GNC_DOT_DIR/gnucashrc"
fi

#Don't quote $EXTRA_ARGS or it will turn into a single arg and fail.
$EXEC "$bundle_contents/MacOS/$name-bin" $EXTRA_ARGS "$@"