# Common home-manager config
{ config, lib, pkgs, ... }:

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

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

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

  user-principals = username:
    map (realm: "${username}@${realm}") (user-realms username);

  user-k5login = username: userOpts: let
    principals = userOpts.k5login ++ (user-principals username);
  in ''
    ${concatStringsSep "\n" principals}
  '';

  user-config = username: userOpts: {
    home.file.".k5login" = {
      source = pkgs.writeText "${username}-k5login" (user-k5login username userOpts);
    };
  };
  
in {
  config.home-manager.users = mapAttrs user-config config.instance.local-users;
}