#!/bin/bash default_capacity_threshold=50 capacity_threshold_file=$HOME/.config/powerloss-handler/capacity_threshold battery_dir=/sys/class/power_supply/BAT0 status_file=$battery_dir/status capacity_file=$battery_dir/capacity UNIT=powerloss-handler CMD=$0 FORCE_SUSPEND= self_install() { if systemctl --user is-active "$UNIT" >/dev/null then systemctl --user stop "$UNIT" fi systemctl --user reset-failed "$UNIT" 2>/dev/null systemd-run --user \ --unit "$UNIT" \ --property Restart="on-failure" \ -- "$CMD" } self_test() { FORCE_SUSPEND=y go echo } do_suspend() { systemctl suspend } go() { read capacity < "$capacity_file" || return case "$capacity" in '' | *[^0-9]*) echo "Error: unexpected value for battery capacity: $capacity" >&2 return 1 ;; esac read status < "$status_file" || return if [ "$FORCE_SUSPEND" ] then status=Discharging capacity=0 echo 'Warning: test: pretending battery is discharging at 0% capacity' >&2 fi if [ -t 2 ] then printf '\r %20s %.2d%%\r' "$status" "$capacity" >&2 fi if [ -f "$capacity_threshold_file" ] then read capacity_threshold < "$capacity_threshold_file" else capacity_threshold=$default_capacity_threshold fi [ "$status" = Discharging ] || return 0 if [ "$capacity" -lt "$capacity_threshold" ] then do_suspend fi } main() { if [ -e /usr/lib/bash/sleep ] then enable -f /usr/lib/bash/sleep sleep else echo 'Warning: not found: /usr/lib/bash/sleep (try: "sudo apt install bash-builtins")' >&2 fi while true do go sleep 1 done } if [ $# = 0 ] then main else case "$1" in run) main ;; install) self_install ;; test) self_test ;; *) echo "Error: unknown command: $*" >&2 echo "Valid commands: run install test" >&2 exit 1 ;; esac fi