all repos

dotfiles @ e8e029dc0a00170703529299d080febe93716719

i use rach linux btw

dotfiles/bin/power-monitor.sh (view raw)

1
#!/usr/bin/env bash
2
# ~~stolen~~ inspired by https://github.com/linuxmobile/kaku/blob/niri/home/services/system/power-monitor.nix
3
4
set -euo pipefail
5
6
STARTUP_WAIT=0
7
8
log() {
9
  echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" >&2
10
}
11
12
get_battery_path() {
13
  local bat_path
14
  bat_path=$(echo /sys/class/power_supply/BAT*)
15
  if [[ ! -d "$bat_path" ]]; then
16
    log "No battery found"
17
    exit 1
18
  fi
19
  echo "$bat_path"
20
}
21
22
readonly BAT
23
BAT="$(get_battery_path)"
24
25
readonly BAT_STATUS="$BAT/status"
26
readonly BAT_CAP="$BAT/capacity"
27
readonly LOW_BAT_PERCENT=30
28
29
readonly AC_PROFILE="performance"
30
readonly BAT_PROFILE="balanced"
31
readonly LOW_BAT_PROFILE="power-saver"
32
33
for file in "$BAT_STATUS" "$BAT_CAP"; do
34
  if [[ ! -f "$file" ]]; then
35
    log "Required file not found: $file"
36
    exit 1
37
  fi
38
done
39
40
if ! command -v powerprofilesctl >/dev/null 2>&1; then
41
  log "powerprofilesctl not found"
42
  exit 1
43
fi
44
45
if [[ -n "${STARTUP_WAIT:-}" ]]; then
46
  sleep "$STARTUP_WAIT"
47
fi
48
49
get_power_profile() {
50
  local status capacity
51
  status=$(cat "$BAT_STATUS")
52
  capacity=$(cat "$BAT_CAP")
53
54
  if [[ "$status" == "Discharging" ]]; then
55
    if [[ "$capacity" -gt $LOW_BAT_PERCENT ]]; then
56
      echo "$BAT_PROFILE"
57
    else
58
      echo "$LOW_BAT_PROFILE"
59
    fi
60
  else
61
    echo "$AC_PROFILE"
62
  fi
63
}
64
65
apply_profile() {
66
  local profile=$1
67
  log "Setting power profile to $profile"
68
  if ! powerprofilesctl set "$profile"; then
69
    log "Failed to set power profile"
70
    return 1
71
  fi
72
}
73
74
log "Starting power monitor"
75
prev_profile=""
76
77
while true; do
78
  current_profile=$(get_power_profile)
79
80
  if [[ "$prev_profile" != "$current_profile" ]]; then
81
    apply_profile "$current_profile"
82
    prev_profile=$current_profile
83
  fi
84
85
  if ! inotifywait -qq "$BAT_STATUS" "$BAT_CAP"; then
86
    log "inotifywait failed, sleeping for 5 seconds before retry"
87
    sleep 5
88
  fi
89
done