Use notify-send as root

The automount script is a neat devd based automounter for FreeBSD. Just pkg install automount and all your removable media will mount themselves automatically in /media when you plug them in. It’s very clean. You may also check vumount, a short script that I made to list all removable media and remove the mount point when you unmount them.

It’s possible to configure automount to send a notification to your desktop using notify-send from libnotify. What it does exactly is (as root):

env DISPLAY=:0 notify-send automount "Device '${1}' mounted on '${3}' directory."

Except that it doesn’t work… I started dbus-monitor and tried notify-send as root (from ttyv2) but didn’t receive anything and notify-send did not complain. So I tried to start dbus-monitor from root instead, in the hope that it would be a bit more verbose than notify-send. I got this error message:

Failed to open connection to session message bus: Did not receive a reply. Possible causes include: the remote application did not send a reply, the message bus security policy blocked the reply, the reply timeout expired, or the network connection was broken.

By default DBus sessions are private and don’t accept connections from other users than the one that own the bus, even root. The solution is to configure DBus to allow root on the session bus. Edit /usr/local/etc/dbus-1/session.conf and add this line to the default policy:

<allow user="root"/>

But you still need tell DBus how to connect to the session bus. To do so you have to specify the session bus address in DBUS_SESSION_BUS_ADDRESS. Fortunately automount is a shell script, so you can fetch and export the bus address from its configuration file. Just add this to /usr/local/etc/automount.conf:

# Load DBus session bus address
DBUS_USER=your-user
if [ -d /home/$DBUS_USER/.dbus/session-bus ]
then
  dbus_file=$(ls -t1 /home/$DBUS_USER/.dbus/session-bus | head -n1)
  export DBUS_SESSION_BUS_ADDRESS=$(cat /home/$DBUS_USER/.dbus/session-bus/$dbus_file | \
                                    grep "DBUS_SESSION_BUS_ADDRESS=" | \
                                    sed 's/[A-Z_]*=//')
fi