how to #shutdown when #AC #PSU #power is #disconnected and running on #battery

useful for media art installations where you don't want the laptop battery to be destroyed by excessive power consumption if there is a long power cut

```
$ cat /usr/local/bin/psu-hotplug.sh
#!/bin/bash
ACTIVE="${1}"
PSUUSER=myinstallationuser
XUSER="$(who | grep -F "(:0)" | cut -d\ -f 1)"
if [ "x${XUSER}" = "x${PSUUSER}" ]
then
if [ "x${ACTIVE}" = "x0" ]
then
# power off if power is not restored
echo "$(date --iso=s) power lost" >> /var/log/psu-hotplug.log
touch /var/run/psu-hotplug.shutdown
sleep 30
if [ -f /var/run/psu-hotplug.shutdown ]
then
echo "$(date --iso=s) shutting down" >> /var/log/psu-hotplug.log
shutdown now -h
else
echo "$(date --iso=s) not shutting down" >> /var/log/psu-hotplug.log
fi
else
echo "$(date --iso=s) power restored" >> /var/log/psu-hotplug.log
rm -f /var/run/psu-hotplug.shutdown
fi
fi
$ cat /etc/udev/rules.d/50-psu-hotplug.rules
SUBSYSTEM=="power_supply", ENV{POWER_SUPPLY_ONLINE}!="0", RUN+="/usr/local/bin/psu-hotplug.sh 1"
SUBSYSTEM=="power_supply", ENV{POWER_SUPPLY_NAME}=="AC", ENV{POWER_SUPPLY_ONLINE}!="0", RUN+="/usr/local/bin/psu-hotplug.sh 1"
```

#linux #udev #hotplug

more udev rules that might be necessary to get it to work properly (seems the AC rule doesn't work reliably alone):

```
SUBSYSTEM=="power_supply", ENV{POWER_SUPPLY_NAME}=="BAT0", ENV{POWER_SUPPLY_STATUS}=="Discharging", RUN+="/usr/local/bin/psu-hotplug.sh 0"
SUBSYSTEM=="power_supply", ENV{POWER_SUPPLY_NAME}=="BAT0", ENV{POWER_SUPPLY_STATUS}!="Discharging", RUN+="/usr/local/bin/psu-hotplug.sh 1"
```