diff options
author | u <u@billy> | 2023-04-09 10:31:57 -0400 |
---|---|---|
committer | u <u@billy> | 2023-04-09 10:31:57 -0400 |
commit | d03defeecd0377373ad5c6d8efe0ff8b6aa844ee (patch) | |
tree | c634c1bd5e2c7f67310171503e7324ada3664e8f |
initial
-rwxr-xr-x | go.sh | 58 |
1 files changed, 58 insertions, 0 deletions
@@ -0,0 +1,58 @@ | |||
1 | #!/bin/sh | ||
2 | capacity_threshold=90 | ||
3 | |||
4 | battery_dir=/sys/class/power_supply/BAT0 | ||
5 | status_file=$battery_dir/status | ||
6 | capacity_file=$battery_dir/capacity | ||
7 | |||
8 | UNIT=powerloss-handler | ||
9 | CMD=$0 | ||
10 | |||
11 | self_install() | ||
12 | { | ||
13 | systemctl --user reset-failed "$UNIT" 2>/dev/null | ||
14 | systemd-run --user \ | ||
15 | --unit "$UNIT" \ | ||
16 | --property Restart="on-failure" \ | ||
17 | -- "$CMD" | ||
18 | } | ||
19 | |||
20 | go() | ||
21 | { | ||
22 | |||
23 | read capacity < "$capacity_file" || return | ||
24 | case "$capacity" in | ||
25 | '' | *[^0-9]*) | ||
26 | echo "Error: unexpected value for battery capacity: $capacity" >&2 | ||
27 | return 1 ;; | ||
28 | esac | ||
29 | |||
30 | if [ -t 2 ] | ||
31 | then | ||
32 | printf ' %.2d%% \r' "$capacity" >&2 | ||
33 | fi | ||
34 | |||
35 | read status < "$status_file" || return | ||
36 | [ "$status" = Discharging ] || return 0 | ||
37 | |||
38 | if [ "$capacity" -lt "$capacity_threshold" ] | ||
39 | then | ||
40 | systemctl suspend | ||
41 | fi | ||
42 | } | ||
43 | |||
44 | main() | ||
45 | { | ||
46 | while true | ||
47 | do | ||
48 | go | ||
49 | sleep 1 | ||
50 | done | ||
51 | } | ||
52 | |||
53 | if [ "$1" = install ] | ||
54 | then | ||
55 | self_install | ||
56 | else | ||
57 | main | ||
58 | fi | ||