#!/bin/sh
# Starts the Endovelicus Gallery for the applications-menu, desktop and autostart launchers. A graphical launcher
# swallows everything a program prints, so if the Gallery dies at startup (a missing desktop library, no display,
# a crash) it would just seem to do nothing. This wrapper keeps the Gallery's output in a log and tells the user.
appdir=$(dirname -- "$(readlink -f -- "$0")")
state=${XDG_STATE_HOME:-${HOME:-/tmp}/.local/state}/endovelicus
log=$state/gallery.log
mkdir -p -- "$state" 2>/dev/null || { state=${TMPDIR:-/tmp}; log=$state/endovelicus-gallery-${USER:-user}.log; }
if [ -f "$log" ] && [ "$(wc -c < "$log" 2>/dev/null || echo 0)" -gt 262144 ]; then mv -f -- "$log" "$log.old"; fi
{ printf '\n--- %s: Endovelicus Gallery starting (%s)\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$*"; } >> "$log" 2>/dev/null

"$appdir/Endovelicus-Gallery" "$@" >> "$log" 2>&1
rc=$?
case "$rc" in 0|129|130|137|143) exit "$rc" ;; esac   # a normal exit, or the session ending it

missing=
for lib in "$appdir/libSkiaSharp.so" "$appdir/libHarfBuzzSharp.so"; do
  [ -f "$lib" ] && command -v ldd >/dev/null 2>&1 && missing="$missing $(ldd "$lib" 2>/dev/null | sed -n 's/^[[:space:]]*\(lib[^ ]*\) => not found.*/\1/p')"
done
if [ -z "$(printf '%s' "$missing" | tr -d ' ')" ] && [ -z "${DISPLAY:-}${WAYLAND_DISPLAY:-}" ]; then
  reason="There is no graphical display available (DISPLAY is not set)."
elif [ -n "$(printf '%s' "$missing" | tr -d ' ')" ]; then
  reason="Required system libraries are missing:$missing
Debian/Ubuntu: sudo apt install libx11-6 libfontconfig1 libfreetype6 libice6 libsm6
Fedora/RHEL:   sudo dnf install libX11 fontconfig freetype libICE libSM"
else
  reason="The Gallery stopped unexpectedly (exit status $rc)."
fi
message="Endovelicus Gallery could not start.

$reason

Details: $log"

printf '%s\n' "$message" >> "$log" 2>/dev/null
printf '%s\n' "$message" >&2
case " $* " in
  *" --tray "*) command -v notify-send >/dev/null 2>&1 && notify-send -a "Endovelicus Gallery" -i endovelicus "Endovelicus Gallery could not start" "$reason" ;;
  *)
    if command -v zenity >/dev/null 2>&1; then zenity --error --no-markup --title="Endovelicus Gallery" --text="$message" 2>/dev/null
    elif command -v kdialog >/dev/null 2>&1; then kdialog --title "Endovelicus Gallery" --error "$message" 2>/dev/null
    elif command -v notify-send >/dev/null 2>&1; then notify-send -a "Endovelicus Gallery" -i endovelicus -u critical "Endovelicus Gallery could not start" "$reason (details: $log)"
    elif command -v xmessage >/dev/null 2>&1; then xmessage -center "$message" 2>/dev/null
    fi ;;
esac
exit "$rc"
