# Jellyfin (native NixOS service). Local media: /var/lib/media (group `media`; jellyfin + server).
# Dashboard: Movies → /var/lib/media/movies, Shows → /var/lib/media/tv (see nixdesk-nfs-client.nix
# for bulk libraries on nixdesk at /mnt/nixdesk-jellyfin/{movies,tv}).
# Do not use "Mixed Movies and Shows" (deprecated): https://jellyfin.org/docs/general/server/media/mixed-movies-and-shows
# Dedicated disk: fileSystems."/var/lib/media" in hardware.nix, then fix ownership.
{ lib, ... }:
{
  nixpkgs.overlays = [
    (final: prev: {
      jellyfin-web = prev.jellyfin-web.overrideAttrs (oldAttrs: {
        postInstall =
          (oldAttrs.postInstall or "")
          + ''
            # Blank default Jellyfin banner assets (read-only store otherwise). Wildcards
            # track hashed filenames across jellyfin-web releases; bump if layout changes.
            find "$out" -type f \( -name 'banner-light.*.png' -o -name 'banner-dark.*.png' \) \
              -exec truncate -s 0 {} \;
          '';
      });
    })
  ];

  users.groups.media = { };

  users.users.jellyfin.extraGroups = [ "media" ];
  users.users.server.extraGroups = [ "media" ];

  systemd.tmpfiles.settings."nix-server-var-lib-media" = {
    "/var/lib/media"."d" = {
      mode = "0775";
      user = "root";
      group = "media";
    };
    "/var/lib/media/movies"."d" = {
      mode = "0775";
      user = "root";
      group = "media";
    };
    "/var/lib/media/tv"."d" = {
      mode = "0775";
      user = "root";
      group = "media";
    };
  };

  services.jellyfin = {
    enable = true;
    openFirewall = true;
  };

  # `users.users.jellyfin.extraGroups` does not affect systemd; the service must list
  # supplementary groups explicitly. Without `media`, directories mode 775 root:media are
  # not writable by uid jellyfin (it only had group `jellyfin`), so deletes fail.
  systemd.services.jellyfin.serviceConfig = {
    SupplementaryGroups = [ "media" ];
    # Jellyfin libraries on NFS (e.g. /mnt/nixdesk-jellyfin). PrivateUsers breaks
    # uid mapping for NFS auth in practice; disable so metadata writes use the real jellyfin uid
    # (squashed to olivier:nfsmedia on nixdesk exports).
    PrivateUsers = lib.mkForce false;
  };
}
