summaryrefslogtreecommitdiff
path: root/go.sh
blob: d68c00264e3fa049f86d6fe33521e1b61ea5cc45 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#!/bin/sh
capacity_threshold=90

battery_dir=/sys/class/power_supply/BAT0
status_file=$battery_dir/status
capacity_file=$battery_dir/capacity

UNIT=powerloss-handler
CMD=$0

self_install()
{
    systemctl --user reset-failed "$UNIT" 2>/dev/null
    systemd-run --user \
                --unit "$UNIT" \
                --property Restart="on-failure" \
                -- "$CMD"
}

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 [ -t 2 ]
    then
        printf '\r  %20s   %.2d%%\r' "$status" "$capacity" >&2
    fi

    [ "$status" = Discharging ] || return 0
    if [ "$capacity" -lt "$capacity_threshold" ]
    then
        systemctl suspend
    fi
}

main()
{
    while true
    do
        go
        sleep 1
    done
}

if [ "$1" = install ]
then
    self_install
else
    main
fi