summaryrefslogtreecommitdiffstats
path: root/krebs/3modules/power-action.nix
blob: 7227f4a9a1c0d73f16c1508ec01a42e191e0bd9d (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
{ config, lib, pkgs, ... }:

with config.krebs.lib;

let
  cfg = config.krebs.power-action;

  out = {
    options.krebs.power-action = api;
    config = lib.mkIf cfg.enable imp;
  };

  api = {
    enable = mkEnableOption "power-action";
    battery = mkOption {
      type = types.str;
      default = "BAT0";
    };
    user = mkOption {
      type = types.string;
      default = "power-action";
    };
    startAt = mkOption {
      type = types.str;
      default = "*:0/1";
    };
    plans = mkOption {
      type = with types; attrsOf (submodule {
        options = {
          charging = mkOption {
            type = nullOr bool;
            default = null;
            description = ''
              check for charging status.
              null = don't care
              true = only if system is charging
              false = only if system is discharging
            '';
          };
          upperLimit = mkOption {
            type = int;
          };
          lowerLimit = mkOption {
            type = int;
          };
          action = mkOption {
            type = path;
          };
        };
      });
    };
  };

  imp = {
    systemd.services.power-action = {
      serviceConfig = rec {
        ExecStart = startScript;
        User = cfg.user;
      };
      startAt = cfg.startAt;
    };
  };

  startScript = pkgs.writeDash "power-action" ''
    set -euf

    power="$(${powerlvl})"
    state="$(${state})"
    ${concatStringsSep "\n" (mapAttrsToList writeRule cfg.plans)}
  '';
  charging_check = plan:
    if (plan.charging == null) then "" else
      if plan.charging
        then ''&& [ "$state" = "true" ]''
        else ''&& ! [ "$state" = "true" ]''
    ;

  writeRule = _: plan:
    "if [ $power -ge ${toString plan.lowerLimit} ] && [ $power -le ${toString plan.upperLimit} ] ${charging_check plan}; then ${plan.action}; fi";

  powerlvl = pkgs.writeDash "powerlvl" ''
    cat /sys/class/power_supply/${cfg.battery}/capacity
  '';

  state = pkgs.writeDash "state" ''
    if [ "$(cat /sys/class/power_supply/${cfg.battery}/status)" = "Discharging" ]
      then echo "false"
      else echo "true"
    fi
  '';

in out