{ config, pkgs, ... }:

{
  c3d2 = {
    deployment.server = "server10";
    hq.sendmail = true;
  };

  networking.hostName = "vaultwarden";

  services = {
    backup = {
      enable = true;
      paths = [ "/var/lib/vaultwarden/" ];
      exclude = [
        "/var/lib/vaultwarden/icon_cache/"
        "/var/lib/vaultwarden/tmp/"
      ];
    };

    bitwarden-directory-connector-cli = {
      enable = true;
      inherit (config.services.vaultwarden) domain;
      ldap = {
        ad = false;
        hostname = "auth.c3d2.de";
        port = 636;
        rootPath = "dc=c3d2,dc=de";
        ssl = true;
        startTls = false;
        username = "uid=search,ou=users,dc=c3d2,dc=de";
      };
      secrets = {
        bitwarden = {
          client_path_id = config.sops.secrets."bwdc/client-id".path;
          client_path_secret = config.sops.secrets."bwdc/client-secret".path;
        };
        ldap = config.sops.secrets."bwdc/ldap-password".path;
      };
      sync = {
        creationDateAttribute = "";
        groups = true;
        groupFilter = "(cn=vaultwarden-*)";
        groupNameAttribute = "cn";
        groupObjectClass = "groupOfNames";
        groupPath = "ou=groups";
        largeImport = false;
        memberAttribute = "member";
        overwriteExisting = false;
        removeDisabled = true;
        revisionDateAttribute = "";
        useEmailPrefixSuffix = false;
        userEmailAttribute = "mail";
        userFilter = "(isMemberOf=cn=vaultwarden-users,ou=groups,dc=c3d2,dc=de)";
        userObjectClass = "person";
        userPath = "ou=users";
        users = true;
      };
    };

    nginx = {
      enable = true;
      virtualHosts."vaultwarden.c3d2.de" = {
        forceSSL = true;
        enableACME = true;
      };
    };

    portunus.addToHosts = true;

    postgresql = {
      package = pkgs.postgresql_16;
      upgrade.stopServices = [ "vaultwarden" ];
    };

    vaultwarden = {
      enable = true;
      config = {
        PUSH_ENABLED = true;
        PUSH_IDENTITY_URI = "https://identity.bitwarden.eu";
        PUSH_RELAY_URI = "https://push.bitwarden.eu";
        SENDMAIL_COMMAND = "/run/wrappers/bin/sendmail";
        SMTP_DEBUG = false;
        SMTP_FROM = "noreply@c3d2.de";
        SMTP_FROM_NAME = "Vaultwarden";
        SHOW_PASSWORD_HINT = false;
        SIGNUPS_ALLOWED = false;
        USE_SENDMAIL = true;
      };
      dbBackend = "postgresql";
      domain = "vaultwarden.c3d2.de";
      environmentFile = config.sops.secrets."vaultwarden/environment".path;
    };
  };

  sops = {
    defaultSopsFile = ./secrets.yaml;
    secrets = {
      "bwdc/client-id".owner = "bwdc";
      "bwdc/client-secret".owner = "bwdc";
      "bwdc/ldap-password".owner = "bwdc";
      "vaultwarden/environment".owner = "vaultwarden";
    };
  };

  system.stateVersion = "23.11";
}
