diff options
Diffstat (limited to 'go.sh')
-rwxr-xr-x | go.sh | 104 |
1 files changed, 0 insertions, 104 deletions
@@ -1,104 +0,0 @@ | |||
1 | #!/bin/bash | ||
2 | default_capacity_threshold=50 | ||
3 | capacity_threshold_file=$HOME/.config/powerloss-handler/capacity_threshold | ||
4 | |||
5 | battery_dir=/sys/class/power_supply/BAT0 | ||
6 | status_file=$battery_dir/status | ||
7 | capacity_file=$battery_dir/capacity | ||
8 | |||
9 | UNIT=powerloss-handler | ||
10 | CMD=$0 | ||
11 | |||
12 | FORCE_SUSPEND= | ||
13 | |||
14 | self_install() | ||
15 | { | ||
16 | if systemctl --user is-active "$UNIT" >/dev/null | ||
17 | then | ||
18 | systemctl --user stop "$UNIT" | ||
19 | fi | ||
20 | systemctl --user reset-failed "$UNIT" 2>/dev/null | ||
21 | systemd-run --user \ | ||
22 | --unit "$UNIT" \ | ||
23 | --property Restart="on-failure" \ | ||
24 | -- "$CMD" | ||
25 | } | ||
26 | |||
27 | self_test() | ||
28 | { | ||
29 | FORCE_SUSPEND=y | ||
30 | go | ||
31 | echo | ||
32 | } | ||
33 | |||
34 | do_suspend() | ||
35 | { | ||
36 | systemctl suspend | ||
37 | } | ||
38 | |||
39 | go() | ||
40 | { | ||
41 | read capacity < "$capacity_file" || return | ||
42 | case "$capacity" in | ||
43 | '' | *[^0-9]*) | ||
44 | echo "Error: unexpected value for battery capacity: $capacity" >&2 | ||
45 | return 1 ;; | ||
46 | esac | ||
47 | read status < "$status_file" || return | ||
48 | |||
49 | if [ "$FORCE_SUSPEND" ] | ||
50 | then | ||
51 | status=Discharging | ||
52 | capacity=0 | ||
53 | echo 'Warning: test: pretending battery is discharging at 0% capacity' >&2 | ||
54 | fi | ||
55 | |||
56 | if [ -t 2 ] | ||
57 | then | ||
58 | printf '\r %20s %.2d%%\r' "$status" "$capacity" >&2 | ||
59 | fi | ||
60 | |||
61 | if [ -f "$capacity_threshold_file" ] | ||
62 | then | ||
63 | read capacity_threshold < "$capacity_threshold_file" | ||
64 | else | ||
65 | capacity_threshold=$default_capacity_threshold | ||
66 | fi | ||
67 | |||
68 | [ "$status" = Discharging ] || return 0 | ||
69 | if [ "$capacity" -lt "$capacity_threshold" ] | ||
70 | then | ||
71 | do_suspend | ||
72 | fi | ||
73 | } | ||
74 | |||
75 | main() | ||
76 | { | ||
77 | if [ -e /usr/lib/bash/sleep ] | ||
78 | then | ||
79 | enable -f /usr/lib/bash/sleep sleep | ||
80 | else | ||
81 | echo 'Warning: not found: /usr/lib/bash/sleep (try: "sudo apt install bash-builtins")' >&2 | ||
82 | fi | ||
83 | |||
84 | while true | ||
85 | do | ||
86 | go | ||
87 | sleep 1 | ||
88 | done | ||
89 | } | ||
90 | |||
91 | if [ $# = 0 ] | ||
92 | then | ||
93 | main | ||
94 | else | ||
95 | case "$1" in | ||
96 | run) main ;; | ||
97 | install) self_install ;; | ||
98 | test) self_test ;; | ||
99 | *) echo "Error: unknown command: $*" >&2 | ||
100 | echo "Valid commands: run install test" >&2 | ||
101 | exit 1 | ||
102 | ;; | ||
103 | esac | ||
104 | fi | ||