{ config, lib, libS, ... }:

{
  c3d2.deployment.server = "server10";

  system.stateVersion = "22.05";

  networking = {
    hostName = "auth";
    firewall.allowedTCPPorts = [
      636 # ldaps
    ];
  };

  services = {
    dex.settings.oauth2.skipApprovalScreen = true;

    nginx = {
      enable = true;
      virtualHosts."auth.c3d2.de" = {
        default = true;
        forceSSL = true;
        enableACME = true;
        locations = {
          "/".proxyPass = "http://localhost:${toString config.services.portunus.port}";
          "/dex".proxyPass ="http://localhost:${toString config.services.portunus.dex.port}";
        };
      };
    };

    portunus = {
      enable = true;
      dex = {
        enable = true;
        oidcClients = [ {
          callbackURL = "https://grafana.hq.c3d2.de/login/generic_oauth";
          id = "grafana";
        } ];
      };
      ldap = {
        searchUserName = "search";
        suffix = "dc=c3d2,dc=de";
        tls = true;
      };
      seedPath = ./seed.json;
    };
  };

  sops = {
    defaultSopsFile = ./secrets.yaml;
    secrets."dex/environment" = libS.sops.permissionForUser "dex";
    secrets."portunus/users/admin-password" = libS.sops.permissionForUser "portunus";
    secrets."portunus/users/search-password" = libS.sops.permissionForUser "portunus";
  };

  systemd.services.dex.serviceConfig = {
    DynamicUser = lib.mkForce false;
    EnvironmentFile = config.sops.secrets."dex/environment".path;
    StateDirectory = "dex";
    User = "dex";
  };

  users = {
    groups.dex = { };
    users.dex = {
      group = "dex";
      isSystemUser = true;
    };
  };
}
