summaryrefslogtreecommitdiff
path: root/bin/xuserrun
blob: 6ec24350c22328183f5a94ae2e08a4ebf517b292 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#!/bin/bash

#
# Run a command as the currently active X11 user 
#

# source: https://github.com/rephorm/xuserrun

seat="seat0"

# determine location of loginctl
LOGINCTL=$(command -v loginctl || command -v systemd-loginctl)
if [[ -e LOGINCTL ]]; then
  echo "Error: Unable to find loginctl executable"
  exit 1
fi

get_session_info() {
  local session="$1"
  local varname="$2"
  local IFS=$'\n'
  eval declare -Ag $varname 
  for row in $(loginctl show-session "$session"); do
    key="$(echo "${row}"|cut -d= -f1)"
    val="$(echo "${row}"|cut -d= -f2-)"
    eval ${varname}[\"${key}\"]=\"${val}\"
  done
}

escape() {
  for arg in "$@" ; do
    printf "%q " "$arg";
  done;
}

active_session="$(loginctl show-seat ${seat}|grep ActiveSession|cut -d= -f2)"
if [[ $? -ne 0 || -z $active_session ]]; then
  echo "Error: Unable to determine active session"
  exit 1
fi

get_session_info $active_session session_info

if [[ ${session_info[Type]} != "x11" ]]; then
  echo "Error: Active session is not x11"
  exit 2
fi

current_user="$(id -u -n)"

if [[ ${current_user} == ${session_info[Name]} ]]; then
  # already correct user, no need to su
  DISPLAY="${session_info[Display]}" "$@"
else
  # run command as user 
  DISPLAY="${session_info[Display]}" su -c - "${session_info[Name]}" "$(escape "$@")"
fi