#!/bin/bash

set -eu

if [ -z "${SUDO_USER:-}" ]; then
  exec sudo $0 "$@"
fi

force_last=false
if [ "${1:-}" = '--force' ]; then
  force_last=true
  shift
fi

default_path=
declare -a choices user_ids

gdm_xauthority_files=$(ls -rt /run/user/*/gdm/Xauthority 2>/dev/null || true)

if [ -z "$gdm_xauthority_files" ]; then
  for xauthority in /run/lightdm/root/*; do
    test -e "$xauthority" || continue
    display=${xauthority#/run/lightdm/root/}
    exec env "DISPLAY=${display}" "XAUTHORITY=${xauthority}" "$@"
  done
  # We are guessing DISPLAY without XAUTHORITY
  exec env DISPLAY=:0 "$@"
fi

echo 'The following user sessions are available:'
echo

i=0
for xauthority in $gdm_xauthority_files; do
  test -e "$xauthority" || continue
  user_dir=${xauthority%/gdm/Xauthority}
  user_id=${user_dir#/run/user/}
  user_name=$(id -nu "$user_id" 2>/dev/null || true)
  tty=$(ps --no-headers -C Xorg -o uid,tty | awk -v uid="$user_id" 'uid == $1 { print $2 }')

  # XXX surprising dependency on exact command-line characteristics
  gnome_shell_pid=$(pgrep -u "$user_id" -fnx '/usr/bin/gnome-shell.distrib' \
		      2>/dev/null || true)
  if [ -n "$gnome_shell_pid" ]; then
    display=$(awk 'BEGIN { FS = "="; RS = "\0" } /^DISPLAY=/ { print $2 }' \
      /proc/${gnome_shell_pid}/environ 2>/dev/null || true)
    if [ -n "$display" ]; then
      i=$(($i + 1))
      choices[$i]="env DISPLAY=$display XAUTHORITY=$xauthority"
      user_ids[$i]="$user_id"
      echo "    $i) $user_name ($user_id) on $tty DISPLAY=$display"
    fi
  fi
done

if [ $i -eq 0 ]; then
  echo 'No accessible user sessions available' >&2
  exit 1
elif [ $i -eq 1 ]; then
  echo
  echo 'Choosing the only session.'
  choice=1
elif $force_last; then
  choice=$i
else
  echo
  choice=
  while [ -z "$choice" ] || [ "$choice" -lt 1 -o "$choice" -gt "$i" ]; do
    read -p "> Your choice: [$i] " choice
    [ -z "$choice" ] && choice=$i
    choice=$(echo "$choice" | awk '/^[0-9]+$/ { print $1 }')
  done
fi

echo "${choices[$choice]} $@"

case "${1:-}" in
  x11vnc)
    # "x11vnc" needs special treatment
    # (must be wrapped through "sudo -u" to work)
    exec sudo -u "#${user_ids[$choice]}" ${choices[$choice]} "$@"
    ;;
  *)
    exec ${choices[$choice]} "$@"
    ;;
esac
