1{
2 config,
3 lib,
4 utils,
5 pkgs,
6 ...
7}:
8let
9
10 cfg = config.systemd.shutdownRamfs;
11
12 ramfsContents = pkgs.writeText "shutdown-ramfs-contents.json" (builtins.toJSON cfg.storePaths);
13
14in
15{
16 options.systemd.shutdownRamfs = {
17 enable = lib.mkEnableOption "pivoting back to an initramfs for shutdown" // {
18 default = true;
19 };
20 contents = lib.mkOption {
21 description = "Set of files that have to be linked into the shutdown ramfs";
22 example = lib.literalExpression ''
23 {
24 "/lib/systemd/system-shutdown/zpool-sync-shutdown".source = writeShellScript "zpool" "exec ''${zfs}/bin/zpool sync"
25 }
26 '';
27 type = utils.systemdUtils.types.initrdContents;
28 };
29
30 storePaths = lib.mkOption {
31 description = ''
32 Store paths to copy into the shutdown ramfs as well.
33 '';
34 type = utils.systemdUtils.types.initrdStorePath;
35 default = [ ];
36 };
37 };
38
39 config = lib.mkIf cfg.enable {
40 systemd.shutdownRamfs.contents = {
41 "/shutdown".source = "${config.systemd.package}/lib/systemd/systemd-shutdown";
42 "/etc/initrd-release".source = config.environment.etc.os-release.source;
43 "/etc/os-release".source = config.environment.etc.os-release.source;
44 };
45 systemd.shutdownRamfs.storePaths = [
46 pkgs.runtimeShell
47 "${pkgs.coreutils}/bin"
48 ]
49 ++ map (c: builtins.removeAttrs c [ "text" ]) (builtins.attrValues cfg.contents);
50
51 systemd.mounts = [
52 {
53 what = "tmpfs";
54 where = "/run/initramfs";
55 type = "tmpfs";
56 options = "mode=0700";
57 }
58 ];
59
60 systemd.services.generate-shutdown-ramfs = {
61 description = "Generate shutdown ramfs";
62 wantedBy = [ "shutdown.target" ];
63 before = [ "shutdown.target" ];
64 unitConfig = {
65 DefaultDependencies = false;
66 RequiresMountsFor = "/run/initramfs";
67 ConditionFileIsExecutable = [
68 "!/run/initramfs/shutdown"
69 ];
70 };
71
72 serviceConfig = {
73 Type = "oneshot";
74 ProtectSystem = "strict";
75 ReadWritePaths = "/run/initramfs";
76 ExecStart = "${pkgs.makeInitrdNGTool}/bin/make-initrd-ng ${ramfsContents} /run/initramfs";
77 };
78 };
79 };
80}