#!/bin/sh
# This file is part of Epoptes, https://epoptes.org
# Copyright 2012-2018 the Epoptes team, see AUTHORS.
# SPDX-License-Identifier: GPL-3.0-or-later

usage() {
    printf "Usage: export \$($0)\n%s" \
"
Output DISPLAY and XAUTHORITY for the current user's X screen.
A root user can then use those to access the user's display.
"
}

die() {
    printf "%s\n" "$@" >&2
    exit 1
}

exit_if_found() {
    # Check if DISPLAY/XAUTHORITY are valid.
    # XAUTHORITY may even be empty, in which case it must not be exported.
    test -n "$DISPLAY" || return
    export DISPLAY XAUTHORITY
    test -n "$XAUTHORITY" || unset XAUTHORITY
    if timeout 1 xwininfo -root -size >/dev/null 2>&1; then
        echo "DISPLAY=$DISPLAY"
        test -n "$XAUTHORITY" && echo "XAUTHORITY=$XAUTHORITY"
        exit 0
    else
        unset DISPLAY XAUTHORITY
    fi
}

if [ $# -gt 0 ]; then
    die "$(usage)"
fi

# Plan A: check if the variables are already set
exit_if_found

# Plan B: check if we can get the info from some well-known process
# Oneliner to discover suitable processes:
# ps -o pid,user:13,comm,cmd $(grep -sl DISPLAY= /proc/[0-9]*/environ |
#     cut -d/ -f3) | sort -n | less
# Tests on Ubuntu 18.04 and some other distros:
# LTSP greeter: ldm
# Ubuntu greeter: dbus-daemon|pulseaudio (same in Fedora and CentOS)
# Ubuntu session: dbus-daemon|pulseaudio (same when locked)
# Ubuntu MATE greeter: lightdm-greeter
# Ubuntu MATE session: dbus-daemon|pulseaudio (same when locked)
# Kubuntu greeter: sddm-greeter|dbus-daemon|pulseaudio
# Kubuntu session: dconf-service|dbus-daemon|pulseaudio (same when locked)
# Lubuntu greeter: lightdm-greeter (same when locked)
# Lubuntu session: dconf-service|pulseaudio (no dbus!)
# Xubuntu greeter: lightdm-greeter (same when locked)
# Xubuntu session: dconf-service|dbus-daemon|pulseaudio (no root process!)
# Sylvia greeter: lightdm-greeter|dbus-daemon
# Sylvia session: dbus-daemon|pulseaudio (same when locked)
# Debian stretch MATE greeter: lightdm-gtk-gre|dbus-daemon
# Debian stretch MATE session: dbus-daemon|dconf-service|pulseaudio
for p in $(pgrep -x 'ldm|lightdm-greeter|dbus-daemon|dconf-service|pulseaudio' |
    sort -rn)
do
    # The first DISPLAY= is only there to prevent a possible syntax error
    export DISPLAY="$DISPLAY" $(tr '\0' '\n' 2>/dev/null < /proc/$p/environ |
        egrep '^DISPLAY=|^XAUTHORITY=')
    exit_if_found
done

# Plan C: Try all processes!
for p in $(pgrep '' | sort -rn); do
    # The first DISPLAY= is only there to prevent a possible syntax error
    export DISPLAY="$DISPLAY" $(tr '\0' '\n' 2>/dev/null < /proc/$p/environ |
        egrep '^DISPLAY=|^XAUTHORITY=')
    exit_if_found
done

# Plan D: give up!
echo "DISPLAY=
XAUTHORITY="
die "Could not detect or access the active display"
