Created
December 3, 2022 11:50
-
-
Save ercoppa/7fd246e847ad03a3bd1203fe30956fd0 to your computer and use it in GitHub Desktop.
sleep_if_inactive_on_battery.sh
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
function notify-send() { | |
# Detect the name of the display in use | |
local display=":$(ls /tmp/.X11-unix/* | sed 's#/tmp/.X11-unix/X##' | head -n 1)" | |
# Detect the user using such display | |
local user=$(who | grep '('$display')' | awk '{print $1}' | head -n 1) | |
# Detect the id of the user | |
local uid=$(id -u $user) | |
sudo -u $user DISPLAY=$display DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$uid/bus notify-send "$@" | |
} | |
status=$(cat /sys/class/power_supply/BAT0/status) | |
# Exit if not discharging | |
if [ "${status}" != "Discharging" ]; then | |
exit 0 | |
fi | |
monitor_status=$(xset q | grep "Monitor is") | |
# Exit if monitor is on | |
if [[ "${monitor_status}" == *"On"* ]]; then | |
exit 0 | |
fi | |
current_x_inactivity_ms=$(xprintidle) | |
# X inactivity time (msecs) | |
x_inactivity_action_ms=300000 # 10 minutes | |
if [ "${current_x_inactivity_ms}" -ge ${x_inactivity_action_ms} ]; then | |
notify-send "Suspend due to inactivity" | |
sleep 30 | |
systemctl suspend | |
exit 0 | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment