{ config, lib, libC, ... }:

{
  c3d2.deployment.server = "server10";

  system.stateVersion = "22.05";

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

  services = {
    backup = {
      enable = true;
      paths = [ "/var/lib/portunus/" ];
    };

    dex.settings.oauth2.skipApprovalScreen = true;

    nginx = {
      enable = true;
      virtualHosts."auth.c3d2.de" = {
        forceSSL = true;
        enableACME = true;
        listen = libC.defaultListen;
        locations = {
          "/".proxyPass = "http://127.0.0.1:${toString config.services.portunus.port}";
          "/dex".proxyPass = "http://127.0.0.1:${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;
      };
      port = 5555;
      removeAddGroup = true;
      seedGroups = true;
      seedSettings = {
        groups = [
          {
            long_name = "Portunus Administrators";
            name = "admins";
            members = [ "admin" ];
            permissions.portunus.is_admin = true;
          }
          {
            long_name = "Search";
            name = "search";
            members = [ "search" ];
            permissions.ldap.can_read = true;
          }
        ];
        users = [
          {
            family_name = "Administrator";
            given_name = "Initial";
            login_name = "admin";
            password.from_command = [ "/usr/bin/env" "cat" "/run/secrets/portunus/users/admin-password" ];
          }
          {
            email = "search@c3d2.de";
            family_name = "-";
            given_name = "Search";
            login_name = "search";
            password.from_command = [ "/usr/bin/env" "cat" "/run/secrets/portunus/users/search-password" ];
          }
        ];
      };
    };
  };

  sops = {
    defaultSopsFile = ./secrets.yaml;
    secrets = {
      "dex/environment".owner = "dex";
      "portunus/users/admin-password".owner = "portunus";
      "portunus/users/search-password".owner = "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;
    };
  };
}
