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

# Himmelblau: Microsoft Entra ID authentication for Linux
#
# Authenticates Linux users against the digistate.nl Entra ID tenant.
# Users log in with their Entra ID credentials via OIDC Device Authorization
# Grant flow (browser-based) or the native PAM orchestrator.
#
# Requires:
#   - A working Entra ID tenant with digistate.nl as a verified domain
#   - An OIDC app registration (Himmelblau client) in the tenant
#   - Network connectivity to login.microsoftonline.com
#
# References:
#   - https://himmelblau-idm.org/docs/
#   - https://github.com/himmelblau-idm/himmelblau

let
  cfg = config.work.himmelblau;
in {
  imports = [
    inputs.himmelblau.nixosModules.himmelblau
  ];

  options.work.himmelblau = {
    enable = lib.mkEnableOption "Himmelblau Entra ID authentication" // {
      default = false;
    };
  };

  config = lib.mkIf cfg.enable {
    services.himmelblau = {
      enable = true;
      settings = {
        domain = [ "digistate.nl" ];
        # Uncomment and set to Entra ID group Object IDs or names to
        # restrict which users can authenticate:
        # pam_allow_groups = [ "ENTRA-GROUP-GUID-HERE" ];
      };
    };

    # Himmelblau registers an NSS module (system.nssModules) for user/group lookups,
    # which requires nscd to be enabled. Keep it on.
    # services.nscd.enable = lib.mkForce false;

    # Expose the aad-tool CLI for diagnostics and enrollment
    environment.systemPackages = [
      inputs.himmelblau.packages.${pkgs.system}.aad-tool
    ];
  };
}
