#!/bin/sh
# AppImage entry point: runs the game with the bundled Python, GTK 4 and libadwaita.
# `AppRun --python ARGS...` runs the bundled interpreter instead (debugging, build checks).
HERE=$(dirname "$(readlink -f "$0")")

# Isolate the bundled Python from the host's Python settings.
for v in $(env | sed -n 's/^\(PYTHON[A-Z_]*\)=.*/\1/p'); do unset "$v"; done
export PYTHONHOME="$HERE/usr"
export PYTHONPATH="$HERE/usr/share/crapette"
export PYTHONDONTWRITEBYTECODE=1

export LD_LIBRARY_PATH="$HERE/usr/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
export GI_TYPELIB_PATH="$HERE/usr/lib/girepository-1.0"
export GIO_MODULE_DIR="$HERE/usr/lib/gio/modules"
export GSETTINGS_SCHEMA_DIR="$HERE/usr/share/glib-2.0/schemas"
export XDG_DATA_DIRS="$HERE/usr/share:${XDG_DATA_DIRS:-/usr/local/share:/usr/share}"

# gdk-pixbuf needs absolute loader paths, and the mount point changes on every run.
cache="${XDG_CACHE_HOME:-$HOME/.cache}/crapette-appimage"
mkdir -p "$cache" 2>/dev/null || cache=$(mktemp -d)
"$HERE/usr/bin/gdk-pixbuf-query-loaders" "$HERE"/usr/lib/gdk-pixbuf-2.0/loaders/*.so \
  > "$cache/loaders.cache" 2>/dev/null
export GDK_PIXBUF_MODULE_FILE="$cache/loaders.cache"

if [ "${1:-}" = "--python" ]; then
  shift
  exec "$HERE/usr/bin/python3" -s "$@"
fi

# Desktop integration for the current user: a launcher and icon in ~/.local/share, so the
# dock, the app grid and the window show the game's icon. Refreshed at each launch (the
# AppImage may have moved). Disable with CRAPETTE_NO_INTEGRATION=1;
# remove with `Crapette-x86_64.AppImage --remove-integration`.
data="${XDG_DATA_HOME:-$HOME/.local/share}"
desktop="$data/applications/crapette-appimage.desktop"
icon="$data/icons/hicolor/scalable/apps/crapette-appimage.svg"
if [ "${1:-}" = "--remove-integration" ]; then
  rm -f "$desktop" "$icon"
  echo "Crapette (AppImage): launcher and icon removed."
  exit 0
fi
if [ -n "${APPIMAGE:-}" ] && [ -z "${CRAPETTE_NO_INTEGRATION:-}" ]; then
  if mkdir -p "$data/applications" "$data/icons/hicolor/scalable/apps" 2>/dev/null; then
    cmp -s "$HERE/fr.bbrose.Crapette.svg" "$icon" || cp "$HERE/fr.bbrose.Crapette.svg" "$icon"
    tmp="$desktop.tmp.$$"
    {
      echo "[Desktop Entry]"
      echo "Type=Application"
      echo "Name=Crapette (AppImage)"
      echo "GenericName=Jeu de cartes"
      echo "Comment=Jouez à la Crapette contre l'ordinateur"
      echo "Exec=\"$APPIMAGE\""
      echo "TryExec=$APPIMAGE"
      echo "Icon=crapette-appimage"
      echo "Terminal=false"
      echo "Categories=Game;CardGame;"
      echo "StartupWMClass=fr.bbrose.Crapette"
      echo "X-AppImage-Integrated=true"
    } > "$tmp"
    if cmp -s "$tmp" "$desktop"; then rm -f "$tmp"; else mv -f "$tmp" "$desktop"; fi
  fi
fi
exec "$HERE/usr/bin/python3" -s -m crapette "$@"
