···11+{ config, pkgs, lib, ... }:
22+33+{
44+ config = lib.mkIf (config.boot.initrd.enable && config.boot.initrd.systemd.enable) {
55+ # Copy secrets into the initrd if they cannot be appended
66+ boot.initrd.systemd.contents = lib.mkIf (!config.boot.loader.supportsInitrdSecrets)
77+ (lib.mapAttrs' (dest: source: lib.nameValuePair "/.initrd-secrets/${dest}" { source = if source == null then dest else source; }) config.boot.initrd.secrets);
88+99+ # Copy secrets to their respective locations
1010+ boot.initrd.systemd.services.initrd-nixos-copy-secrets = lib.mkIf (config.boot.initrd.secrets != {}) {
1111+ description = "Copy secrets into place";
1212+ # Run as early as possible
1313+ wantedBy = [ "sysinit.target" ];
1414+ before = [ "cryptsetup-pre.target" ];
1515+ unitConfig.DefaultDependencies = false;
1616+1717+ # We write the secrets to /.initrd-secrets and move them because this allows
1818+ # secrets to be written to /run. If we put the secret directly to /run and
1919+ # drop this service, we'd mount the /run tmpfs over the secret, making it
2020+ # invisible in stage 2.
2121+ script = ''
2222+ for secret in $(cd /.initrd-secrets; find . -type f); do
2323+ mkdir -p "$(dirname "/$secret")"
2424+ cp "/.initrd-secrets/$secret" "/$secret"
2525+ done
2626+ '';
2727+2828+ unitConfig = {
2929+ Type = "oneshot";
3030+ RemainAfterExit = true;
3131+ };
3232+ };
3333+ # The script needs this
3434+ boot.initrd.systemd.extraBin.find = "${pkgs.findutils}/bin/find";
3535+ };
3636+}