1{ config, lib, ... }:
2
3with lib;
4
5let
6
7 cfg = config.powerManagement;
8
9in
10
11{
12
13 ###### interface
14
15 options = {
16
17 powerManagement = {
18
19 enable = mkOption {
20 type = types.bool;
21 default = true;
22 description =
23 lib.mdDoc ''
24 Whether to enable power management. This includes support
25 for suspend-to-RAM and powersave features on laptops.
26 '';
27 };
28
29 resumeCommands = mkOption {
30 type = types.lines;
31 default = "";
32 description = lib.mdDoc "Commands executed after the system resumes from suspend-to-RAM.";
33 };
34
35 powerUpCommands = mkOption {
36 type = types.lines;
37 default = "";
38 example = literalExpression ''
39 "''${pkgs.hdparm}/sbin/hdparm -B 255 /dev/sda"
40 '';
41 description =
42 lib.mdDoc ''
43 Commands executed when the machine powers up. That is,
44 they're executed both when the system first boots and when
45 it resumes from suspend or hibernation.
46 '';
47 };
48
49 powerDownCommands = mkOption {
50 type = types.lines;
51 default = "";
52 example = literalExpression ''
53 "''${pkgs.hdparm}/sbin/hdparm -B 255 /dev/sda"
54 '';
55 description =
56 lib.mdDoc ''
57 Commands executed when the machine powers down. That is,
58 they're executed both when the system shuts down and when
59 it goes to suspend or hibernation.
60 '';
61 };
62
63 };
64
65 };
66
67
68 ###### implementation
69
70 config = mkIf cfg.enable {
71
72 systemd.targets.post-resume = {
73 description = "Post-Resume Actions";
74 requires = [ "post-resume.service" ];
75 after = [ "post-resume.service" ];
76 wantedBy = [ "sleep.target" ];
77 unitConfig.StopWhenUnneeded = true;
78 };
79
80 # Service executed before suspending/hibernating.
81 systemd.services.pre-sleep =
82 { description = "Pre-Sleep Actions";
83 wantedBy = [ "sleep.target" ];
84 before = [ "sleep.target" ];
85 script =
86 ''
87 ${cfg.powerDownCommands}
88 '';
89 serviceConfig.Type = "oneshot";
90 };
91
92 systemd.services.post-resume =
93 { description = "Post-Resume Actions";
94 after = [ "suspend.target" "hibernate.target" "hybrid-sleep.target" "suspend-then-hibernate.target" ];
95 script =
96 ''
97 /run/current-system/systemd/bin/systemctl try-restart --no-block post-resume.target
98 ${cfg.resumeCommands}
99 ${cfg.powerUpCommands}
100 '';
101 serviceConfig.Type = "oneshot";
102 };
103
104 };
105
106}