#!/bin/sh
# Works even when the frozen UI cannot load its Python or OpenGL libraries.
set -u
STATE_DIR="${XDG_STATE_HOME:-$HOME/.local/state}/Photobok"
mkdir -p "$STATE_DIR" || exit 1
chmod 700 "$STATE_DIR" 2>/dev/null || true
REPORT="$STATE_DIR/linux-package-diagnostics.txt"
umask 077
{
  echo 'Photobok Linux package diagnostics'
  date -u '+Time UTC: %Y-%m-%dT%H:%M:%SZ'
  uname -srm
  if [ -r /etc/os-release ]; then
    sed -n '/^PRETTY_NAME=/p' /etc/os-release
  fi
  echo "Session type: ${XDG_SESSION_TYPE:-unknown}"
  echo "Desktop: ${XDG_CURRENT_DESKTOP:-unknown}"
  echo "DISPLAY set: $(if [ -n "${DISPLAY:-}" ]; then echo yes; else echo no; fi)"
  echo "WAYLAND_DISPLAY set: $(if [ -n "${WAYLAND_DISPLAY:-}" ]; then echo yes; else echo no; fi)"
  if command -v lspci >/dev/null 2>&1; then
    lspci | grep -Ei 'VGA|3D controller|Display controller' || true
  fi
  if command -v glxinfo >/dev/null 2>&1; then
    if command -v timeout >/dev/null 2>&1; then
      timeout 5 glxinfo -B 2>&1 || true
    fi
  fi
  if command -v dpkg-query >/dev/null 2>&1; then
    dpkg-query -W -f='Package: ${Package} ${Version} ${Status}\n' photobok 2>/dev/null || true
  fi
  if [ -r /opt/photobok/Photobok ]; then
    echo 'Executable: installed'
    if command -v file >/dev/null 2>&1; then file /opt/photobok/Photobok; fi
    if command -v ldd >/dev/null 2>&1; then ldd /opt/photobok/Photobok; fi
    for library in /opt/photobok/_internal/kivy/core/window/_window_sdl2*.so; do
      if [ -f "$library" ] && command -v ldd >/dev/null 2>&1; then
        echo "Kivy window provider: $library"
        ldd "$library" || true
      fi
    done
  else
    echo 'Executable: missing or unreadable'
  fi
  echo 'Startup log location: ~/.local/state/Photobok/startup.log (or XDG_STATE_HOME)'
  echo 'No passwords, payment keys, photos, or configuration contents are collected.'
} > "$REPORT"
echo "$REPORT"
if [ "${1:-}" = '--open-report' ]; then
  if command -v xdg-open >/dev/null 2>&1; then
    xdg-open "$REPORT" >/dev/null 2>&1 && exit 0
  fi
  if command -v zenity >/dev/null 2>&1; then
    zenity --text-info --title='Photobok Diagnostics' --filename="$REPORT" >/dev/null 2>&1 || true
  fi
fi
