#!/bin/sh
set -eu
base=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
show_error() {
  message=$1
  printf '%s\n' "$message" >&2
  if command -v zenity >/dev/null 2>&1; then
    zenity --error --no-markup --text="$message" || :
  elif command -v xmessage >/dev/null 2>&1; then
    xmessage "$message" || :
  elif command -v notify-send >/dev/null 2>&1; then
    notify-send 'WinMx4u Linux Chat' "$message" || :
  fi
}
if ! /usr/bin/python3 -E -s -c 'import gi; gi.require_foreign("cairo"); gi.require_version("Gdk", "3.0"); gi.require_version("Gtk", "3.0"); from gi.repository import Gdk, Gtk' >/dev/null 2>&1; then
  show_error 'WinMx4u Linux Chat requires Python 3, PyGObject with Cairo support, and GTK 3. On Debian or Ubuntu, the .deb installer can install these dependencies.'
  exit 1
fi
umask 077
cache=${XDG_CACHE_HOME:-"$HOME/.cache"}/winmx4u
if ! mkdir -p "$cache"; then
  cache=${TMPDIR:-/tmp}
fi
if ! log=$(mktemp "$cache/winmx4u-startup.XXXXXX"); then
  exec /usr/bin/python3 -E -s "$base/desktop.py"
fi
trap 'rm -f -- "$log"' EXIT
if /usr/bin/python3 -E -s "$base/desktop.py" 2>"$log"; then
  exit 0
else
  status=$?
fi
trap - EXIT
if ! /usr/bin/python3 -E -s - "$log" <<'PY'
import sys
from pathlib import Path

import gi
gi.require_version("Gdk", "3.0")
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk

log = Path(sys.argv[1])
detail = log.read_text(encoding="utf-8", errors="replace").strip().splitlines()
dialog = Gtk.MessageDialog(message_type=Gtk.MessageType.ERROR, buttons=Gtk.ButtonsType.CLOSE,
                           text="WinMx4u Linux Chat could not open.")
dialog.format_secondary_text((detail[-1] if detail else "The desktop process exited unexpectedly.")
                             + "\n\nStartup log: " + str(log))
dialog.run()
dialog.destroy()
PY
then
  show_error "WinMx4u Linux Chat could not open. Startup log: $log"
fi
exit "$status"
