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

with lib;

let
  cfg = config.lass.power-action;

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

  api = {
    enable = mkEnableOption "power-action";
    user = mkOption {
      type = types.user;
      default = {
        name = "power-action";
      };
    };
    startAt = mkOption {
      type = types.str;
      default = "*:0/1";
    };
    plans = mkOption {
      type = with types; attrsOf (submodule {
        options = {
          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;
    };
    users.users.${cfg.user.name} = {
      inherit (cfg.user) name uid;
    };
  };

  startScript = pkgs.writeDash "power-action" ''
    power="$(${powerlvl})"
    ${concatStringsSep "\n" (mapAttrsToList writeRule cfg.plans)}
  '';

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

  powerlvl = pkgs.writeDash "powerlvl" ''
    cat /sys/class/power_supply/BAT0/capacity
  '';

in out