]> code.delx.au - monosys/blob - bin/xuserrun
Moved xuserrun from scripts repo
[monosys] / bin / xuserrun
1 #!/bin/bash
2 # vim:ts=2:sts=2:sw=2
3
4 #
5 # Run a command as the currently active X11 user
6 #
7
8 seat="seat0"
9
10 # determine location of loginctl
11 LOGINCTL=$(command -v loginctl || command -v systemd-loginctl)
12 if [[ -e LOGINCTL ]]; then
13 echo "Error: Unable to find loginctl executable"
14 exit 1
15 fi
16
17 get_session_info() {
18 local session="$1"
19 local varname="$2"
20 local IFS=$'\n'
21 eval declare -Ag $varname
22 for row in $(loginctl show-session "$session"); do
23 key="$(echo "${row}"|cut -d= -f1)"
24 val="$(echo "${row}"|cut -d= -f2-)"
25 eval ${varname}[\"${key}\"]=\"${val}\"
26 done
27 }
28
29 escape() {
30 for arg in "$@" ; do
31 printf "%q " "$arg";
32 done;
33 }
34
35 session_list="$(loginctl --no-legend | grep "$seat" | awk '{print $1}')"
36 found_active_session=""
37 for session in $session_list; do
38 get_session_info "$session" session_info
39 if [[ "${session_info[Active]}" = "yes" ]]; then
40 found_active_session="yes"
41 break
42 fi
43 done
44 if [ -z "${found_active_session}" ]; then
45 echo "Error: Unable to determine active session"
46 exit 1
47 fi
48
49 if [[ "${session_info[Type]}" != "x11" ]]; then
50 echo "Error: Active session is not x11"
51 exit 2
52 fi
53
54 current_user="$(id -u -n)"
55
56 if [[ ${current_user} == ${session_info[Name]} ]]; then
57 # already correct user, no need to su
58 DISPLAY="${session_info[Display]}" "$@"
59 else
60 # run command as user
61 DISPLAY="${session_info[Display]}" su -c - "${session_info[Name]}" "$(escape "$@")"
62 fi