#!/bin/sh
set -eu

APPDIR="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
export APPDIR
export PATH="$APPDIR/usr/bin:$PATH"
export PYTHONHOME="$APPDIR/usr"

PYTHONPATH_ENTRIES=""
for PYTHON_DIR in $(find "$APPDIR/usr/lib" -maxdepth 1 -type d -name 'python3.*' | sort -V -r); do
    for PYTHON_SUBDIR in site-packages dist-packages; do
        PYTHON_PATH="$PYTHON_DIR/$PYTHON_SUBDIR"
        if [ -d "$PYTHON_PATH" ]; then
            PYTHONPATH_ENTRIES="${PYTHONPATH_ENTRIES:+$PYTHONPATH_ENTRIES:}$PYTHON_PATH"
        fi
    done
done

export PYTHONPATH="$PYTHONPATH_ENTRIES${PYTHONPATH:+:$PYTHONPATH}"
export LD_LIBRARY_PATH="$APPDIR/usr/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
export GI_TYPELIB_PATH="$APPDIR/usr/lib/girepository-1.0${GI_TYPELIB_PATH:+:$GI_TYPELIB_PATH}"
export GSETTINGS_SCHEMA_DIR="$APPDIR/usr/share/glib-2.0/schemas"
export XDG_DATA_DIRS="$APPDIR/usr/share:${XDG_DATA_DIRS:-/usr/local/share:/usr/share}"

if [ -d "$APPDIR/usr/lib/gstreamer-1.0" ]; then
    export GST_PLUGIN_SYSTEM_PATH="$APPDIR/usr/lib/gstreamer-1.0${GST_PLUGIN_SYSTEM_PATH:+:$GST_PLUGIN_SYSTEM_PATH}"
fi

if [ -f "$APPDIR/usr/lib/gdk-pixbuf-2.0/2.10.0/loaders.cache" ]; then
    export GDK_PIXBUF_MODULEDIR="$APPDIR/usr/lib/gdk-pixbuf-2.0/2.10.0/loaders"
    export GDK_PIXBUF_MODULE_FILE="$APPDIR/usr/lib/gdk-pixbuf-2.0/2.10.0/loaders.cache"
fi

exec "$APPDIR/usr/bin/python3" "$APPDIR/usr/bin/meshy" "$@"
