#!/bin/sh
# postinst — start the KylinBot daemon immediately after install/upgrade.
#
# Login autostart and crash-restart are handled by the XDG autostart entry
# (/etc/xdg/autostart/kylin-bot-autostart.desktop, X-UKUI-AutoRestart=true).
# This script only covers the "已登录用户装完即用、无需注销重登" gap by
# launching the daemon once inside each currently active graphical session.
set -e

BIN=/usr/bin/kylin-bot

start_for_active_sessions() {
    [ -x "$BIN" ] || return 0
    command -v loginctl >/dev/null 2>&1 || return 0

    # Enumerate unique UIDs that currently own a session.
    loginctl list-sessions --no-legend 2>/dev/null | awk '{print $2}' | sort -u | while read -r uid; do
        [ -n "$uid" ] || continue
        user=$(id -nu "$uid" 2>/dev/null) || continue
        [ "$user" = "root" ] && continue

        runtime="/run/user/$uid"
        [ -d "$runtime" ] || continue

        # Skip if this user already has a daemon running.
        if pgrep -u "$user" -f "$BIN daemon" >/dev/null 2>&1; then
            continue
        fi

        su - "$user" -c \
            "DISPLAY=\${DISPLAY:-:0} XDG_RUNTIME_DIR=$runtime \
             DBUS_SESSION_BUS_ADDRESS=unix:path=$runtime/bus \
             nohup $BIN daemon >/dev/null 2>&1 &" || true
    done
}

case "$1" in
    configure)
        start_for_active_sessions
        ;;
    abort-upgrade|abort-remove|abort-deconfigure)
        ;;
esac

#DEBHELPER#

exit 0
