#!/bin/sh
set -e

if [ "$1" = "configure" ]; then
    # Reload udev rules (system-level, runs as root)
    udevadm control --reload-rules 2>/dev/null || true
    # Scoped to SteelSeries (idVendor=1038), the way the Distrobox installers
    # have always done it. Re-adding every USB device on the machine disturbs
    # hardware that has nothing to do with ASM, and — because this runs while
    # asm-daemon still holds the headset's interface with the kernel driver
    # detached — it makes the running daemon lose the device (errno 19) and
    # lets hid-generic claim interface 4 back. The headset then reads as absent
    # until it is physically replugged, after every single upgrade.
    udevadm trigger --action=add --subsystem-match=usb --attr-match=idVendor=1038 2>/dev/null || true
    # And the hidraw nodes the hidraw transport opens: their mode comes from the same rules.
    udevadm trigger --action=add --subsystem-match=hidraw 2>/dev/null || true

    # Upgrade ($2 holds the previous version): apt replaced the files, but the
    # running asm-daemon still holds the old code in memory and would keep
    # serving it until the next reboot.
    if [ -n "${2:-}" ] && [ -x /usr/lib/arctis-sound-manager/restart-user-services.sh ]; then
        /usr/lib/arctis-sound-manager/restart-user-services.sh || true
    fi

    REAL_USER="${SUDO_USER:-}"
    # Mint's and Ubuntu's graphical installers go through pkexec or a root
    # daemon, which set no SUDO_USER: PySide6 was then never pip-installed on
    # series that do not package it, and asm-gui silently failed to open.
    if [ -z "$REAL_USER" ] && [ -n "${PKEXEC_UID:-}" ] && [ "$PKEXEC_UID" != 0 ]; then
        REAL_USER=$(id -nu "$PKEXEC_UID" 2>/dev/null || true)
    fi
    if [ -z "$REAL_USER" ] && command -v loginctl >/dev/null 2>&1; then
        # The one user with an active graphical session; none if ambiguous.
        GRAPHICAL_USERS=$(
            for s in $(loginctl list-sessions --no-legend 2>/dev/null | awk '{print $1}'); do
                loginctl show-session "$s" -p Name -p Type -p Active -p Remote 2>/dev/null \
                    | awk -F= '{v[$1] = $2}
                        END {if ((v["Type"] == "x11" || v["Type"] == "wayland") &&
                                 v["Active"] == "yes" && v["Remote"] == "no" &&
                                 v["Name"] != "" && v["Name"] != "root") print v["Name"]}'
            done | sort -u
        )
        if [ -n "$GRAPHICAL_USERS" ] && [ "$(printf '%s\n' "$GRAPHICAL_USERS" | wc -l)" -eq 1 ]; then
            REAL_USER="$GRAPHICAL_USERS"
        fi
    fi

    # If PySide6 is not available as a system package (e.g. Ubuntu 22.04),
    # install it via pip for the real user who ran sudo.
    if [ -n "$REAL_USER" ] && ! python3 -c "from PySide6 import QtWidgets" 2>/dev/null; then
        echo "  PySide6 not found in system packages — installing via pip for ${REAL_USER}..."
        su -l "$REAL_USER" -c \
            "pip3 install --user --break-system-packages pyside6 2>/dev/null || pip3 install --user pyside6" \
            || echo "  [!] pip install failed — run manually: pip3 install --user pyside6"
    fi

    # Run asm-setup immediately if the user has an active D-Bus session.
    # Falls back to /etc/xdg/autostart/asm-first-run.desktop on next login otherwise.
    if [ -n "$REAL_USER" ]; then
        REAL_UID=$(id -u "$REAL_USER")
        XDG_RUNTIME_DIR="/run/user/$REAL_UID"
        DBUS_SOCKET="$XDG_RUNTIME_DIR/bus"
        if [ -S "$DBUS_SOCKET" ]; then
            echo "  Running asm-setup for ${REAL_USER}..."
            su -l "$REAL_USER" -c \
                "XDG_RUNTIME_DIR=$XDG_RUNTIME_DIR DBUS_SESSION_BUS_ADDRESS=unix:path=$DBUS_SOCKET asm-setup" \
                || echo "  [!] asm-setup failed — run manually: asm-setup"
        else
            echo "  No active session found — asm-setup will run automatically on next login."
        fi
    fi

    echo ""
    echo "  Arctis Sound Manager installed!"
    echo ""
fi

#DEBHELPER#
exit 0
