]> code.delx.au - monosys/commitdiff
Moved xuserrun from scripts repo
authorJames Bunton <jamesbunton@delx.net.au>
Mon, 13 Mar 2017 04:16:27 +0000 (15:16 +1100)
committerJames Bunton <jamesbunton@delx.net.au>
Mon, 13 Mar 2017 04:16:27 +0000 (15:16 +1100)
bin/xuserrun [new file with mode: 0755]

diff --git a/bin/xuserrun b/bin/xuserrun
new file mode 100755 (executable)
index 0000000..d6909ce
--- /dev/null
@@ -0,0 +1,62 @@
+#!/bin/bash
+# vim:ts=2:sts=2:sw=2
+
+#
+# Run a command as the currently active X11 user
+#
+
+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;
+}
+
+session_list="$(loginctl --no-legend | grep "$seat" | awk '{print $1}')"
+found_active_session=""
+for session in $session_list; do
+  get_session_info "$session" session_info
+  if [[ "${session_info[Active]}" = "yes" ]]; then
+    found_active_session="yes"
+    break
+  fi
+done
+if [ -z "${found_active_session}" ]; then
+  echo "Error: Unable to determine active session"
+  exit 1
+fi
+
+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