{
  config,
  pkgs,
  lib,
  ...
}: let
  nextcloud = config.services.nextcloud;
  secrets = config.sops.secrets;
  sops = config.sops;
in {
  sops.secrets = {
    "nextcloud/admin_password" = {
      owner = "nextcloud";
    };
    "nextcloud/oidc_client_secret" = {};
  };
  sops.templates = {
    "nextcloud/secrets.json" = {
      owner = "nextcloud";
      content = builtins.toJSON {
        oidc_login_client_secret = sops.placeholder."nextcloud/oidc_client_secret";
      };
    };
  };

  environment.systemPackages = with pkgs; [ffmpeg];

  services.nextcloud = {
    enable = true;
    https = true;
    package = pkgs.nextcloud31;
    hostName = "files.${config.networking.domain}";
    configureRedis = true;
    database.createLocally = true;
    config = {
      adminpassFile = secrets."nextcloud/admin_password".path;
      dbtype = "pgsql";
    };
    secretFile = sops.templates."nextcloud/secrets.json".path;
    phpOptions."opcache.interned_strings_buffer" = "23";
    settings = {
      maintenance_window_start = 2;
      default_phone_region = "GB";
      # https://github.com/pulsejet/nextcloud-oidc-login
      oidc_login_provider_url = "https://auth.tristans.cloud/application/o/nextcloud/";
      oidc_login_client_id = "Fo0OMWCHBlJNw5DsEI0IzeCk0HpU1TIZpy3D5Tix";
      oidc_login_button_text = "Log in with Authentik";
      oidc_login_use_id_token = true;
      oidc_login_attributes = {
        id = "preferred_username";
        name = "name";
        mail = "email";
        groups = "groups";
        is_admin = "NextcloudAdmin";
        login_filter = "groups";
      };
      oidc_login_filter_allowed_values = {
        "0" = "Nextcloud users";
      };
      oidc_login_use_external_storage = false;
      oidc_login_scope = "email openid profile NextcloudAdmin";
      oidc_login_proxy_ldap = false;
      oidc_login_disable_registration = false;
      oidc_login_redir_fallback = false;
      oidc_login_tls_verify = true;
      oidc_create_groups = true;
      oidc_login_webdav_enabled = true;
      oidc_login_public_key_caching_time = 604800;
      oidc_login_min_time_between_jwks_requests = 10;
      oidc_login_well_known_caching_time = 86400;
      datadirectory = "/mnt/storage/nextcloud";
    };
    extraApps = {
      inherit
        (config.services.nextcloud.package.packages.apps)
        contacts
        calendar
        mail
        gpoddersync
        memories
        notes
        # maps
        previewgenerator
        deck
        news
        oidc_login
        recognize
        ;
    };
    maxUploadSize = "5G";
  };
  services.nginx.virtualHosts.${nextcloud.hostName} = {
    forceSSL = true;
    enableACME = true;
  };
}
