#!/bin/sh
#
# Send notification message to all locally logged in users.
#
# Specification:
#   http://www.galago-project.org/specs/notification/0.9/index.html
#
# Uses notify-send from libnotify-bin, but could be rewritten to use
# pynotify and python if it is a better idea.
#
# Author: Petter Reinholdtsen, based on code from Trond Hasle Amundsen
#
# License: GPL v2 or later

msg="$1"
title="$2"

if [ -z "$msg" ] ; then
    cat<<EOF
usage: $0 <msg> [title]

Send notification on the session dbus for all logged in users.  The
msg can use some HTML tags like <b> and <i>.

EOF
    exit 1
fi

# Need to be root to find the local users
if [ "$(whoami)" != root ] ; then
    echo "error: This script require root access" 1>&2
    exit 1
fi

if [ ! -x /usr/bin/notify-send ] ; then # from libnotify-bin
    echo "error: unable to find /usr/bin/notify-send" 1>&2
    exit 1
fi

# Find logged in users and their display
usersinfo="$(who | awk '$2 ~ /^:/ { print $1 "%" $2}')"

# Exit if no users with display
if [ -z "$usersinfo" ]; then
    exit 0
fi

for userinfo in $usersinfo ; do
    # Find user, display and homedir
    user="$(echo $userinfo | cut -d% -f1)"
    display="$(echo $userinfo | cut -d% -f2)"
    homedir="$(getent passwd $user | cut -d: -f6)"

    # options for notify-send
    icon="dialog-info"     # simple info icon
    timeout=60000          # timeout 1 min
    urgency="normal"       # low, normal or critical

    # Find DBUS address (needed if notification-daemon is not running)
    for pid in `pgrep -u $user`; do
	if [ -f "/proc/${pid}/environ" ]; then
	    dbus=`grep -z DBUS_SESSION_BUS_ADDRESS /proc/${pid}/environ`
	    [ -n "$dbus" ] && break
	fi
    done

    # Set dbus value properly
    dbus=`echo $dbus | sed 's/DBUS_SESSION_BUS_ADDRESS=//'`

    # send notification
    LANG=C \
	XAUTHORITY=${homedir}/.Xauthority \
	DISPLAY=${display} \
	DBUS_SESSION_BUS_ADDRESS=${dbus} \
	su $user -m -s /bin/sh -c "notify-send -i ${icon} -t ${timeout} -u ${urgency} '${title}' '${msg}'" \
	>/dev/null 2>&1
    retval=$?

    # Log result
    if [ "$retval" = "0" ]; then
	logger -p user.crit -t notify-local-users "info: [$user] notification succeeded"
    else
	logger -p user.crit -t notify-local-users "info: [$user] notification failed"
    fi
done

exit 0
