I have been using the following udev rule and bash script to automatically configure my external monitor for some time now, however recently the script has become unreliable, usually doing the opposite of what it should (ie, when I plug in the external monitor my desktop is only on my laptop screen, when I unplug my external monitor my desktop is spread over two screens).
I've added a noise to the script so that I know it's running each time I (un)plug my HDMI monitor, so I am confident that the udev rule is working properly. I've tried adding a delay in case xrandr is running too soon, and I've added logging, but xrandr doesn't seem to be outputting any errors. The script works properly if I run it manually. Is it possible that xrandr is running before the hardware state is updated, and even with sleep the script is blocking the update?
ACTION=="change", SUBSYSTEM=="drm", RUN+="/usr/bin/hdmi-plugged"
/usr/bin/xrandr --output eDP1 --auto --output HDMI1 --auto --above eDP1