#!/bin/sh
###########################################################################
# Runs the command line parameter as the $SUDO_USER, while ensuring that
# $DBUS_SESSION_BUS_ADDRESS and $DISPLAY are properly set.
#
# Copyright (C) 2010 Alkis Georgopoulos <alkisg@gmail.com>
#
# 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/>.
#
# On Debian GNU/Linux systems, the complete text of the GNU General
# Public License can be found in `/usr/share/common-licenses/GPL'.
###########################################################################

die() {
    echo "sch-scripts error: $@" >&2
    echo "ERROR:sudo: $@" >> /var/log/sch-scripts.log
    exit 1
}

# If sch-scripts passed DBUS_SESSION_BUS_ADDRESS, use it
if [ "$1" = "-dbus" ]; then
    DBUS_SESSION_BUS_ADDRESS="$2"
    shift 2
elif [ -z "$DBUS_SESSION_BUS_ADDRESS" ]; then
    # Get our "grantfather" process, that should contain DBUS_SESSION_BUS_ADDRESS
    # There's a chance it's dead though, so sch-scripts always uses the -dbus param
    DBUS_SESSION_BUS_ADDRESS=$(tr '\0' '\n' < "/proc/$(ps -p $PPID -o ppid:1=)/environ" | sed -n 's/^DBUS_SESSION_BUS_ADDRESS=//p')
    test -n "$DBUS_SESSION_BUS_ADDRESS" || die "could not discover DBUS_SESSION_BUS_ADDRESS"
fi

# First, run this script as the target user
if [ "$(id -u)" -eq 0 ]; then
    test -n "$SUDO_USER" || die "SUDO_USER is not defined"
    SCRIPT="$(cd $(dirname "$0") && pwd)/$(basename "$0")"
    exec sudo -u "$SUDO_USER" DBUS_SESSION_BUS_ADDRESS="$DBUS_SESSION_BUS_ADDRESS" -i "$SCRIPT" "$@"
fi

# Now, check some necessary environment variables
# XAUTHORITY isn't necessary, it defaults to ~/.Xauthority if unset
for var in HOME USER DISPLAY DBUS_SESSION_BUS_ADDRESS; do
    eval value="\$$var"
    test -n "$value" || die "$var is not defined"
done

exec "$@"
