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

let cfg = config.sydnix.deertopia.copyparty;
in {
  options.sydnix.deertopia.copyparty = {
    enable = lib.mkEnableOption "Copyparty";
    port = lib.mkOption {
      type = lib.types.port;
      description = ''
        Port on which Copyparty is to listen.
      '';
      default = 3923;
    };
  };

  config = lib.mkIf cfg.enable {
    sydnix.impermanence.directories = [
    ];

    nixpkgs.overlays = [ inputs.copyparty.overlays.default ];

    # HACK: Ad-hoc permissions, as typical.
    users.users.copyparty.extraGroups = [
      "media"
    ];

    # HACK: Make files created by copyparty.service initialise with the mode
    # 775.
    systemd.services.copyparty.serviceConfig.UMask = lib.mkForce "002";

    services.copyparty = {
      enable = true;
      settings = {
        # These three options (`idp-h-usr`, `idp-h-grp`, `xff-src`) are
        # necessary for SSO integration.

        # The HTTP headers (provided by the coproxy) where Copyparty can expect
        # to find the user's name and groups.
        idp-h-usr = "remote-user";
        idp-h-grp = "remote-groups";
        # For security reasons, Copyparty will only acknowledge those headers
        # when the request comes from a known IP address specified here.  In our
        # case, we tell it to accept requests from any private IP.
        xff-src = "lan";
      };
      volumes = {
        "/Soulseek" = {
          path = "/var/lib/slskd";
          access.r = "*";
        };
        "/Media library" = {
          path = "/persist/media/library";
          # View and upload, but no deleting.
          access.rw = "*";
          access.rwmd = "@jellyfin-admin";
        };
        "/Torrents" = {
          path = "/persist/media/torrents";
          access.r = "*";
          access.rwmd = "@jellyfin-admin";
        };
      };
    };

    sydnix.deertopia.nginx.vhosts."files" = {
      directory = null;
      vhost = {
        forceSSL = true;
        enableACME = true;
        extraConfig = ''
          include ${./authelia/authelia-location.conf};
          # Increase limit of upload sizes.
          client_max_body_size 20G;
        '';
        locations."/".extraConfig = ''
          include ${./authelia/authelia-authrequest.conf};
          include ${./authelia/proxy.conf};
          proxy_pass http://localhost:${builtins.toString cfg.port};
        '';
      };
    };
  };
}
