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

with lib;
let
  list-contains = lst: item: any (i: i == item) lst;

  domain-realm = _: domainOpts: domainOpts.gssapi-realm;

  user-realms = username:
    mapAttrsToList domain-realm
      (filterAttrs
        (domain: domainOpts:
          list-contains domainOpts.local-users username)
        config.fudo.domains);

  admin-realms = username:
    mapAttrsToList domain-realm
      (filterAttrs
        (domain: domainOpts:
          list-contains domainOpts.local-admins username)
        config.fudo.domains);

  user-principals = username: let
    user-princs = map (realm: "${username}@${realm}") (user-realms username);
    admin-princs = map (realm: "${username}/root@${realm}") (admin-realms username);
  in user-princs ++ admin-princs;

  user-k5login = principals: concatStringsSep "\n" principals;

  user-config = username: userOpts: {
    home.file.".k5login".text =
      user-k5login (user-principals username);
  };
in {
  config = {
    home-manager.users = let
      user-configs =
        mapAttrs user-config config.instance.local-users;
      root-config = {
        root = let
          domain-name = config.instance.local-domain;
          realm = config.fudo.domains.${domain-name}.gssapi-realm;
          principals = map (admin: "${admin}/root@${realm}")
            config.instance.local-admins;
        in {
          home.file.".k5login".text =
            user-k5login principals;
        };
      };
    in user-configs // root-config;
  };
}