#!/bin/sh
#
# Author: Aaron Voisine <aaron@voisine.org>
# Inkscape Modifications:
#	Michael Wybrow <mjwybrow@users.sourceforge.net>
#	Jean-Olivier Irisson <jo.irisson@gmail.com>
#

CWD="`(cd \"\`dirname \\\"$0\\\"\`\"; echo $PWD)`"
TOP="`dirname \"$CWD\"`"

export DYLD_LIBRARY_PATH="$TOP/lib"
# add /usr/local/bin which, though standard, don't seem to be in the PATH
PATH="/usr/local/bin:$PATH"
# add python from MacPython http://homepages.cwi.nl/~jack/macpython/macpython-osx.html
if [ -d /Library/Frameworks/Python.framework/Versions/Current/bin ]
then
	export PATH="/Library/Frameworks/Python.framework/Versions/Current/bin:$PATH"
fi
# add Fink
if [ -d /sw/bin ]
then
	export PATH="/sw/bin/:$PATH"
fi
# add MacPorts (former DarwinPorts)
if [ -d /opt/local/bin ]
then
	export PATH="/opt/local/bin:$PATH"
fi
export PATH="$CWD:$PATH"
export PANGO_RC_FILE="$HOME/.inkscape-etc/pangorc"
export FONTCONFIG_PATH="$TOP/etc/fonts"
export GTK_IM_MODULE_FILE="$HOME/.inkscape-etc/gtk.immodules"
export GDK_PIXBUF_MODULE_FILE="$HOME/.inkscape-etc/gdk-pixbuf.loaders"
export GTK_DATA_PREFIX="$TOP"
export GTK_EXE_PREFIX="$TOP"
export GNOME_VFS_MODULE_CONFIG_PATH="$TOP/etc/gnome-vfs-2.0/modules"
export GNOME_VFS_MODULE_PATH="$TOP/lib/gnome-vfs-2.0/modules"

export INKSCAPE_SHAREDIR="$TOP"
export INKSCAPE_PLUGINDIR="$TOP/lib/inkscape"
export INKSCAPE_LOCALEDIR="$TOP/locale"

# Set GTK theme (only if there is no .gtkrc-2.0 in the user's home)
if [[ ! -e $HOME/.gtkrc-2.0 ]]; then
	# prepare the theme depending on OS X appearance settings
	HERE=`pwd`
	cd "$INKSCAPE_SHAREDIR/themes/Clearlooks-Quicksilver-OSX/gtk-2.0/"
	./sync_osx_look.sh
	cd "$HERE"
	export GTK2_RC_FILES="$INKSCAPE_SHAREDIR/themes/Clearlooks-Quicksilver-OSX/gtk-2.0/gtkrc"
fi

# TODO: Have to add ".UTF-8" to the LANG since ommiting causes Inkscape
#       to crash on startup in locale_from_utf8().
export LANG="`grep \"\`defaults read .GlobalPreferences AppleCollationOrder \
	2>&1\`_\" /usr/share/locale/locale.alias | tail -n1 | sed 's/\./ /' | \
	awk '{print $2}'`.UTF-8"

# Handle the case where the directory storing Inkscape has a '#' in the name.
# This '#' needs to be escaped in pango.modules for Pango to work properly.
ESCAPEDTOP=`echo $TOP | sed 's/#/\\\\\\\\#/'`

mkdir -p ~/.inkscape-etc
sed 's|${HOME}|'"$HOME|g" "$TOP/etc/pango/pangorc" > ~/.inkscape-etc/pangorc
sed 's|${CWD}|'"$ESCAPEDTOP|g" "$TOP/etc/pango/pango.modules" \
    > ~/.inkscape-etc/pango.modules
cp -f "$TOP/etc/pango/pangox.aliases" ~/.inkscape-etc/
sed 's|${CWD}|'"$TOP|g" "$TOP/etc/gtk-2.0/gtk.immodules" \
    > ~/.inkscape-etc/gtk.immodules
sed 's|${CWD}|'"$TOP|g" "$TOP/etc/gtk-2.0/gdk-pixbuf.loaders" \
    > ~/.inkscape-etc/gdk-pixbuf.loaders

exec "$CWD/inkscape-bin" "$@"
