summaryrefslogtreecommitdiff
path: root/go.sh
blob: b9d6aeaee218a84706b47ae1a9d1294fed67d373 (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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#!/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