I also don’t know everything about it but I can certainly try to explain.
To automate running commands or scripts when attaching or disconnecting devices, you can use udev
for this functionality. It sees when a USB device is attached or disconnected, for instance.
Wikipedia:
udev (userspace /dev) is a device manager for the Linux kernel. As the successor of devfsd and hotplug, udev primarily manages device nodes in the /dev directory. At the same time, udev also handles all user space events raised when hardware devices are added into the system or removed from it, including firmware loading as required by certain devices.
Some more explanation for Arch Linux: udev - ArchWiki
And for Debian: udev - Debian Wiki
For creating rules: Writing udev rules
Those links already explain it way better than I can. What I can add this is not mentioned often: the syntax for the rules file is very strict and does not let you know when you make an error. I recommend starting with very broad filters (attributes, subsystems, etc) and only test with opening an app or sending a message. Look at my example and don’t forget to replace the “user” part of “user@.host” if your user account is named differently. When you get the basic filtering to work, you can increasingly add filters as required if you need it to trigger on a specific device or a type of devices. When it doesn’t work, figure out why.
My rule:
ACTION=="add"
→ When a device is added with the following filters:
SUBSYSTEM=="usb"
→ USB device
ATTR{idVendor}=="18d1", ATTR{idProduct}=="4ee7"
→ A device with this vendor ID and product ID. These correspond to Android ADB drivers, so for me using those drivers, it is detected that an Android smartphone is connected with USB Debug enabled.
ATTR{serial}=="xxxxxxxx"
→ This filters for the specific device that I want to trigger the command on, or it would trigger on each Android smartphone with USB Debug enabled.
RUN+="/usr/bin/systemd-run --machine=user@.host --user notify-send 'Hello' 'Making backups'"
→ This is the command I used to test it working. As I think udev operates as root, so calling an application to open, will not display in the logged in user I guess. This specifically says to send a notification to the “user”-account of the same host-machine. If you want to run more commands, you can just use another RUN+ command at the end, but I recommend to consult the documentation.