{ config, lib, pkgs, ... }:
let
    hostName = (lib.toLower config.networking.hostName) + ".gvfr.de";
in
{
    services.nextcloud = {
        enable = true;
        https = true;
        package = pkgs.nextcloud26;
        hostName = hostName;
        datadir = "/data/nextcloud";
        config = {
            dbtype = "pgsql";
            dbhost = "/run/postgresql";
            adminpassFile = "/secrets/nextcloud_admin_password.txt";
            extraTrustedDomains = [
                ((lib.toLower config.networking.hostName) + ".lan")
                (lib.toLower config.networking.hostName)
            ];
        };
        caching.redis = true;
        enableBrokenCiphersForSSE = false;
    };

    services.postgresql = {
        enable = true;
        ensureUsers = [
            {
                name = "nextcloud";
                ensurePermissions = {
                    "DATABASE nextcloud" = "ALL PRIVILEGES";
                };
            }
            {
                name = "superuser";
                ensurePermissions = {
                    "ALL TABLES IN SCHEMA public" = "ALL PRIVILEGES";
                };
            }
        ];
        ensureDatabases = [ "nextcloud" ];
    };

    # Ensure that postgres is running *before* running the setup
    systemd.services."nextcloud-setup" = {
        requires = ["postgresql.service"];
        after = ["postgresql.service"];
    };

    networking.firewall.allowedTCPPorts = [ 80 443 ];

    services.nginx = {
        virtualHosts.${hostName} = {
            forceSSL = true;
            enableACME = true;
        };
    };

    users.extraGroups.music = {
        members = [ "nextcloud" ];
    };
}
