{ config, lib, pkgs, ... }:
let
    domain = "md.gvfr.de";
in
{
    services.hedgedoc = {
        enable = true;
        environmentFile = "/secrets/hedgedoc.env";
        settings = {
            port = 7000;
            domain = domain;
            protocolUseSSL = true;
            uploadsPath = "/data/hedgedoc/uploads";
            allowGravatar = false;
            db = {
                dialect = "postgres";
                host = "/run/postgresql";
                username = "hedgedoc";
                database = "hedgedoc";
            };
            allowAnonymous = false;
            allowAnonymousEdits = true;
            csp = {
                enable = true;
                directives = {
                    scriptSrc = "gvfr.de";
                };
                upgradeInsecureRequest = "auto";
                addDefaults = true;
            };

            allowEmailRegister = false;
        };
    };

    services.postgresql = {
        enable = true;
        ensureUsers = [
            {
                name = "hedgedoc";
                ensureDBOwnership = true;
            }
        ];
        ensureDatabases = [ "hedgedoc" ];
    };

    services.nginx = {
        enable = true;
        virtualHosts.${domain} = {
            listenAddresses = [ "0.0.0.0" "[::]" ];
            forceSSL = true;
            enableACME = true;
            locations = {
                "/" = {
                    proxyPass = "http://localhost:7000";
                    extraConfig = ''
                        proxy_set_header Host $host; 
                        proxy_set_header X-Real-IP $remote_addr; 
                        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 
                        proxy_set_header X-Forwarded-Proto $scheme;
                    '';
                };
                "/socket.io/" = {
                    proxyPass = "http://localhost:7000";
                    extraConfig = ''
                        proxy_set_header Host $host; 
                        proxy_set_header X-Real-IP $remote_addr; 
                        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 
                        proxy_set_header X-Forwarded-Proto $scheme;
                        proxy_set_header Upgrade $http_upgrade;
                        proxy_set_header Connection $connection_upgrade;
                    '';
                };
            };
        };
    };

    networking.firewall.allowedTCPPorts = [ 80 443 ];
}
