-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbattery_check.spell
executable file
·67 lines (57 loc) · 2.69 KB
/
battery_check.spell
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
#!/bin/sh
# Checks battery life and suspends if it's too low.
if acpi 2>&1 | grep 'power_supply'; then
exit
fi
case "$(hostname)" in tolaria) exit ;; esac
CACHE="/tmp/$LOGNAME"
mkdir -p "$CACHE"
setup() {
batteries_levels=$(acpi -b | cut -d ' ' -f 4 | grep -o '[0-9]*')
batteries_state=$(acpi | grep 'Battery' | sed 's/Battery\s[0-9]*: //' | sed 's/, [0-9][0-9]*\%.*//')
battery_remaining=$(acpi | grep -oh '[0-9:]* remaining' | sed 's/:\w\w remaining$/ Minutes/' | sed 's/00://' | sed 's/:/h /')
num_batteries=$(echo "$batteries_levels" | wc -l)
battery_level=$(echo "$batteries_levels" | awk -v n="$num_batteries" '{s+=$1} END {printf "%.0f\n", s/n}')
# Battery state selection (priority for 'Charging')
battery_state=$(echo "$batteries_state" | awk '{ if($0=="Charging") {r=$0} else {s=$0} } END{if(r=="") {print s} else {print r}}')
if [ ! -f "$CACHE/.battery" ]; then
echo "$battery_level" >$CACHE/.battery
echo "$battery_state" >>$CACHE/.battery
exit
fi
previous_battery_level=$(head -n 1 $CACHE/.battery)
previous_battery_state=$(tail -n 1 $CACHE/.battery)
echo "$battery_level" >$CACHE/.battery
echo "$battery_state" >>$CACHE/.battery
}
checkBatteryLevel() {
[ "$battery_level" = "$previous_battery_level" ] && exit
if [ "$battery_state" != "Discharging" ] && [ "$battery_level" -ge 90 ]; then
notify-send "Battery almost full: ${battery_level}%, unplug" -u low -a "$(basename "$0")"
elif [ "$battery_state" = "Discharging" ]; then
if [ -e $CACHE/use_the_juice ] && [ "$battery_level" -le 5 ]; then
notify-send 'Shutting down' -u critical -a "$(basename "$0")"
shutdown
elif ! [ -e $CACHE/use_the_juice ] && [ "$battery_level" -le 10 ]; then
systemctl suspend
elif [ "$battery_level" -le 20 ]; then
notify-send "Low Battery" "Your computer will suspend soon unless plugged into a power outlet." -u critical -a "$(basename "$0")"
elif [ "$battery_level" -le 30 ]; then
notify-send "Low Battery" "$battery_level% ($battery_remaining) of battery remaining." -u normal -a "$(basename "$0")"
fi
fi
}
checkBatteryStateChange() {
if [ "$battery_state" != "Discharging" ] && [ "$previous_battery_state" = "Discharging" ]; then
notify-send "Charging" "Battery is now plugged in." -u low -a "$(basename "$0")"
fi
if [ "$battery_state" = "Discharging" ] && [ "$previous_battery_state" != "Discharging" ]; then
notify-send "Power Unplugged" "Your computer has been disconnected from power." -u low -a "$(basename "$0")"
fi
}
while :; do
setup
checkBatteryStateChange
checkBatteryLevel
sleep 1m
done