#!/usr/bin/env bash
# SPDX-FileCopyrightText: © 2009 Back In Time Team
#
# SPDX-License-Identifier: CC0-1.0
#
# This file is released under Creative Commons Zero 1.0 (CC0-1.0) and part of
# the program "Back In Time". The program as a whole is released under GNU
# General Public License v2 or any later version (GPL-2.0-or-later).
# See LICENSES directory or go to <https://spdx.org/licenses/CC0-1.0.html>
# and <https://spdx.org/licenses/GPL-2.0-or-later.html>.
if [ "x$XDG_SESSION_TYPE" = "xwayland" ]; then
    # PREFIX="env QT_QPA_PLATFORM=wayland-egl XDG_RUNTIME_DIR=$XDG_RUNTIME_DIR"
    # Empty prefix to use the default Qt platform plugin (normally xcb)
    # to fix #836 and #1350
    PREFIX=""
else
    # X11
    PREFIX=""
fi

ERR_FILE=$(mktemp)

# Catch error message of pkexec if there is one. Might happen if no polkit
# agent is active, e.g. when using IceWM.
# Details:
#    https://github.com/bit-team/backintime/pull/2328#issuecomment-3702705290
# Error message (stderr) of pkexec is written to a temp file
pkexec --disable-internal-agent $PREFIX "/usr/bin/backintime-qt" "$@" 2> "$ERR_FILE"

STATUS=$?

cat "$ERR_FILE" >&2

if (( STATUS )); then
    ERR=$(< "$ERR_FILE")

    # Fancy newline (ANSI-C-Quoting) because of xmessage and bash
    MSG="Error: ${ERR}"$'\n'"Return code: ${STATUS}"
    TITLE="Back In Time: Problems running in root mode"
    FALLBACK=0

    # Use zenity or xmessage
    if command -v zenity >/dev/null 2>&1; then
        zenity --error --title="$TITLE" --no-markup --text="$MSG" || FALLBACK=1
    else
        FALLBACK=1
    fi

    if (( FALLBACK )); then
        xmessage -nearmouse "${TITLE}"$'\n'"${MSG}"
    fi

fi

rm -f "$ERR_FILE"
exit "${STATUS}"
