#!/bin/sh
# Phoenix-Backup Desktop-App starten (Paket phoenix-backup-desktop).
# Die App ist nur die Oberfläche: Sicherungen laufen im Systemdienst
# phoenix-agent; die App verbindet sich über dessen lokalen Socket.
#   phoenix-backup               Fenster öffnen
#   phoenix-backup --autostart   bei der Anmeldung: nur ins Tray (falls vorhanden)
GUI=/usr/lib/phoenix-backup/phoenix-backup-gui
SOCK=/run/phoenix-agent/ipc.sock
GROUP=phoenix-backup
export PHOENIX_IPC_SOCKET="$SOCK"

msg() {
  if command -v zenity >/dev/null 2>&1; then zenity --error --title="Phoenix-Backup" --width=420 --text="$1" 2>/dev/null && return
  elif command -v kdialog >/dev/null 2>&1; then kdialog --title "Phoenix-Backup" --error "$1" 2>/dev/null && return
  elif command -v notify-send >/dev/null 2>&1; then notify-send "Phoenix-Backup" "$1" 2>/dev/null; fi
  echo "Phoenix-Backup: $1" >&2
}

AUTOSTART=0
for a in "$@"; do [ "$a" = "--autostart" ] && AUTOSTART=1; done

# Tray vorhanden? (StatusNotifier-Host: KDE, Cinnamon, XFCE, MATE, Ubuntu-GNOME
# mit AppIndicator-Erweiterung). Ohne Tray startet der Autostart KEIN Fenster —
# die Sicherungen laufen ohnehin im Dienst.
has_tray() {
  command -v dbus-send >/dev/null 2>&1 || return 0
  dbus-send --session --print-reply --dest=org.freedesktop.DBus /org/freedesktop/DBus \
    org.freedesktop.DBus.NameHasOwner string:org.kde.StatusNotifierWatcher 2>/dev/null | grep -q 'boolean true'
}
if [ "$AUTOSTART" = 1 ]; then
  has_tray || exit 0
  set -- --minimized
fi

# Auf den Dienst warten (Autostart direkt nach dem Booten).
i=0
while [ ! -S "$SOCK" ] && [ $i -lt 20 ]; do sleep 1; i=$((i + 1)); done
if [ ! -S "$SOCK" ]; then
  [ "$AUTOSTART" = 1 ] && exit 0
  msg "Der Phoenix-Backup-Dienst läuft nicht. Starten mit: sudo systemctl start phoenix-agent"
  exit 1
fi

if [ "$(id -u)" != 0 ] && [ ! -w "$SOCK" ]; then
  ME=$(id -un)
  # In /etc/group eingetragen, aber diese Sitzung kennt die Gruppe noch nicht
  # (vor dem Neu-Anmelden): sg übernimmt sie ohne Passwort.
  if getent group "$GROUP" | cut -d: -f4 | tr ',' '\n' | grep -qx "$ME" && command -v sg >/dev/null 2>&1; then
    if [ $# -gt 0 ]; then sg "$GROUP" -c "exec $GUI $*"; else sg "$GROUP" -c "exec $GUI"; fi
    rc=$?
  else
    [ "$AUTOSTART" = 1 ] && exit 0
    msg "Ihr Benutzer ($ME) darf den Phoenix-Backup-Dienst nicht bedienen. Ein Administrator schaltet ihn frei mit:  sudo usermod -aG $GROUP $ME   (danach ab- und wieder anmelden)."
    exit 1
  fi
else
  "$GUI" "$@"
  rc=$?
fi
# 3 = Dienst erreichbar, aber antwortet nicht (z. B. zu alter Agent ohne Desktop-Socket).
if [ "$rc" = 3 ] && [ "$AUTOSTART" != 1 ]; then
  msg "Keine Verbindung zum Phoenix-Backup-Dienst. Bitte prüfen: systemctl status phoenix-agent"
fi
exit "$rc"
