{ config, lib, pkgs, ... }:

with lib;
let
  make-passwd-file = hostname:
    pkgs.lib.passwd.stablerandom-passwd-file
      "${hostname}-fudo-client-passwd"
      config.instance.build-seed;

  secrets =
    config.fudo.secrets.host-secrets.${config.instance.hostname};

  host-password-files = mapAttrs (hostname: hostOpts:
    make-passwd-file hostname) config.fudo.hosts;

in {
  config = {
    fudo = {
      secrets.host-secrets = mapAttrs (hostname: hostOpts: {
        backplane-client-passwd = {
          source-file = host-password-files.${hostname};
          target-file = "/var/fudo/backplane-client/passwd";
          user = config.fudo.client.dns.user;
        };
      }) config.fudo.hosts;

      client.dns = {
        password-file =
          secrets.backplane-client-passwd.target-file;
      };

      backplane.client-hosts = mapAttrs (hostname: hostOpts: {
        password-file = host-password-files.${hostname};
      }) config.fudo.hosts;
    };
  };
}