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

{
  c3d2.deployment.server = "server10";

  microvm.mem = 1024;

  networking.hostName = "hedgedoc";

  services = {
    backup.paths = [ "/var/lib/hedgedoc" ];

    hedgedoc = {
      enable = true;
      ldap.enable = true;
      settings = {
        allowAnonymousEdits = true;
        allowFreeURL = true;
        allowOrigin = [ "hedgedoc.c3d2.de" ];
        csp = {
          enable = true;
          addDefaults = true;
          upgradeInsecureRequest = "auto";
        };
        db = {
          dialect = "postgres";
          host = "/run/postgresql/";
        };
        defaultPermission = "freely";
        domain = "hedgedoc.c3d2.de";
        ldap.searchFilter = lib.mkForce "(&(&(objectclass=person)(|(uid={{username}})(mail={{username}})))(isMemberOf=cn=hedgedoc,${config.security.ldap.roleBaseDN}))";
        loglevel = "warn";
        protocolUseSSL = true;
        sessionSecret = "$sessionSecret";
      };
      environmentFile = config.sops.secrets."hedgedoc".path;
    };

    nginx = {
      enable = true;
      enableReload = true;
      virtualHosts = {
        "codimd.c3d2.de" = {
          forceSSL = true;
          enableACME = true;
          locations."/".return = "301 https://hedgedoc.c3d2.de$request_uri";
        };
        "hackmd.c3d2.de" = {
          forceSSL = true;
          enableACME = true;
          locations."/".return = "301 https://hedgedoc.c3d2.de$request_uri";
        };
        "hedgedoc.c3d2.de" = {
          default = true;
          forceSSL = true;
          enableACME = true;
          locations = {
            "^~ /robots.txt".return = "200 'User-agent: *\\nDisallow: /'";
            "/".proxyPass = "http://localhost:${toString config.services.hedgedoc.settings.port}";
          };
        };
      };
    };

    portunus.addToHosts = true;

    postgresql = {
      enable = true;
      ensureDatabases = [
        "hedgedoc"
      ];
      ensureUsers = [ {
        name = "hedgedoc";
        ensurePermissions = {
          "DATABASE \"hedgedoc\"" = "ALL PRIVILEGES";
        };
      }];
      package = pkgs.postgresql_15;
      upgrade.stopServices = [ "hedgedoc" ];
    };
  };

  sops = {
    age.sshKeyPaths = [ "/etc/ssh/ssh_host_ed25519_key" ];
    defaultSopsFile = ./secrets.yaml;
    secrets = {
      "hedgedoc".owner = config.systemd.services.hedgedoc.serviceConfig.User;
      "restic/password".owner = "root";
      "restic/repository/server8".owner = "root";
    };
  };

  system.stateVersion = "22.11";
}
