+#!/bin/sh
+#
+# Execute a command as another user, with access to the X display
+#
+# Copyright (C) 2013 Antonio Ospite <ospite@studenti.unina.it>
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+
+# This is the equivalent of sux[1] but simpler and using sudo,
+# since I don't have su installed on some of my systems.
+#
+# [1] http://fgouget.free.fr/sux/
+
+set -e
+
+usage() {
+ echo "usage: $(basename $0) [OPTION]... <sudo_options>";
+ echo "Execute a command as another user, with access to the X display"
+ echo
+ echo "List of OPTIONs:"
+ echo
+ echo " -u user Execute the program as the specified user (default is root)"
+ echo " -d display Set the X display"
+ echo " -h|--help Show this help text"
+ echo
+ sudo -h | grep -v "^[ ]\+-u user"
+}
+
+USERNAME=root
+
+while true;
+do
+ case "$1" in
+ -u)
+ [ "x$2" != "x" ] || { usage 1>&2; exit 1; }
+ USERNAME="$2"
+ shift 2
+ ;;
+
+ -d)
+ [ "x$2" != "x" ] || { usage 1>&2; exit 1; }
+ DISPLAY="$2"
+ shift 2
+ ;;
+
+ -h | --help)
+ usage
+ exit 0
+ ;;
+
+ *)
+ break
+ ;;
+ esac
+done
+
+id $USERNAME > /dev/null || { echo "Invalid user." 1>&2; exit 1; }
+
+[ -n "$DISPLAY" ] || { echo "Cannot get the DISPLAY env variable." 1>&2; exit 1; }
+
+[ "x$@" != "x" ] || { usage 1>&2; exit 1; }
+
+# Authorize the user
+xauth extract - $DISPLAY | sudo -u "$USERNAME" xauth merge -
+
+# Execute the command.
+# NOTE: -i or -s have to be passed in order to open a shell
+sudo DISPLAY="$DISPLAY" -u "$USERNAME" "$@"