SYNOPSIS

I use a Raspberry Pi 5 as a media player.
My music and movies are stored on an external USB drive, which I sync via Unison.
I want MPD user service to automatically start when this USB drive is plugged in, and gracefully stop when it is unplugged.

On Raspberry Pi OS (Bookworm), udisks2 manages dynamic storage. It watches udev events and exposes disk state changes via D-Bus.
gvfs-udisks2-volume-monitor listens to these D-Bus signals and requests udisks2 to mount the drive under /media/<USER>/<UUID>.


DOCUMENTATION


PROCEDURE

1. Enable MPD Boot Check

To allow MPD to start on boot only if the USB drive is already attached, create a systemd user override.
This prevents MPD from failing or throwing missing directory errors when booting without the drive.

1
2
3
# ~/.config/systemd/user/mpd.service.d/override.conf
[Unit]
ConditionPathIsDirectory=/media/jeyzu/D7CD-633B/Music

2. Configure Hotplug Watcher (Systemd Path Unit)

When a watched directory is removed, the kernel destroys the inotify watch handle associated with it and sends an IN_IGNORED event to systemd.
So to support hotplugging, you must monitor the parent directory /media/jeyzu/ instead of the drive subdirectory.

1
2
3
4
5
6
7
8
9
# ~/.config/systemd/user/media-watch.path
[Unit]
Description=Watch user media directory

[Path]
PathChanged=/media/jeyzu/

[Install]
WantedBy=default.target

3. Create the Service Toggle

Create a helper user service that checks for the existence of the music folder whenever the parent mount path changes, starting or stopping mpd.service accordingly.

1
2
3
4
5
6
7
# ~/.config/systemd/user/media-watch.service
[Unit]
Description=Hotplugging media handler

[Service]
Type=oneshot
ExecStart=%h/bin/media-hotplug

4. Create the associated script

Notice that -M jeyzu@ is not needed because the script executes as USER and inherits DBUS_SESSION_BUS_ADDRESS & XDG_RUNTIME_DIR.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# ~/bin/media-hotplug
#! /usr/bin/bash

MUSIC="/media/jeyzu/D7CD-633B/Music"
if [ -d "${MUSIC}" ]
  then logger "${MUSIC} plugged"
  systemctl --user start mpd.service
else
  logger "${MUSIC} unplugged"
  systemctl --user stop mpd.service
fi


5. Enable Linger and Activate

Ensure user systemd services continue to run in the background even when no active interactive login session is open.

1
2
3
4
5
sudo loginctl enable-linger $USER

systemctl --user daemon-reload
systemctl --user enable mpd.service
systemctl --user enable --now media-watch.path