#!/bin/sh

# Jens Getreu

# `sudox` (`sudo` for X) is a Bash script that executes commands under X in
# UNIX and LINUX on behalf of another user using sudo. It provides  the
# necessary privileges using xauth over a pipe. I use it for example to
# execute firefox as a different user with low privileges.
#
# 
# Usage: 
#
#     > sudox -u <other_user> <command>
# 
# Example:
# 
#     > sudox -u mynobody firefox
#
#
# `sudox` has the same function than the discontinued `sux` command 
# that was distributed formely as a package in Debian and Ubuntu. 
#
#
#
# **Installation:**
#
# To avoid that `sudox` is asking you for a password twice, consider adding a
# line like `%users LOCAL=(mynobody) NOPASSWD:ALL` to `/etc/sudoers`.
#
#
# **References:**
# 
# [Remote X Apps mini-HOWTO](http://www.tldp.org/HOWTO/pdf/Remote-X-Apps.pdf)
#
# [What is a good alternative to the sux command?](https://askubuntu.com/questions/428284/what-is-a-good-alternative-to-the-sux-command#462848)


if  [ $# -lt 3 ] || [ $1 != "-u" ] 
then echo "usage: `basename $0` -u <clientuser> <command>" >&2
     exit 2
fi
shift

CLIENTUSER="$1"
CLIENTHOME=$(grep "^$CLIENTUSER:" /etc/passwd|cut -d: -f 6)
shift

# FD 4 becomes stdin too
exec 4>&0

xauth -b nlist "$DISPLAY" | {

    # FD 3 becomes xauth output
    # FD 0 becomes stdin again
    # FD 4 is closed
    exec 3>&0 0>&4 4>&-

    exec /usr/bin/sudo -H -u "$CLIENTUSER" \
          /usr/bin/xauth -f "$CLIENTHOME"/.Xauthority nmerge - <&3 
}

exec echo "env DISPLAY=$DISPLAY XAUTHORITY=${CLIENTHOME}/.Xauthority $*" \
    | sudo  -i -u "$CLIENTUSER"
