{
  config,
  pkgs,
  ...
}: let
  inherit (config.services.secrets) secrets;
  rcloneMedia = pkgs.writeShellScriptBin "rclone-media" ''
    ${pkgs.rclone}/bin/rclone --config ${secrets.rclone_config.path} "$@"
  '';
  mountMedia = pkgs.writeShellScriptBin "mount-media" ''
    umount -flR /Media || true
    ${rcloneMedia}/bin/rclone-media mount Media-Combine: /Media \
      --allow-other \
      --uid=${toString config.users.users.jellyfin.uid} \
      --gid=${toString config.users.groups.jellyfin.gid} \
      --fast-list \
      --umask=666 \
      --cache-dir=/caches/media \
      --dir-cache-time=1m \
      --vfs-cache-mode=full \
      --vfs-cache-max-size=5g \
      --vfs-cache-max-age=120m \
      --log-level=INFO "$@"
  '';
in {
  environment.systemPackages = with pkgs; [
    rclone
    rcloneMedia
    fuse
    fuse3
    mountMedia
  ];

  programs.fuse.userAllowOther = true;

  systemd.services.jellyfin = {
    wants = ["media-mount.service"];
    after = ["media-mount.service"];
    serviceConfig.ReadWritePaths = "/Media";
  };

  systemd.services.media-mount = {
    wantedBy = ["jellyfin.service"];
    partOf = ["jellyfin.service"];
    path = with pkgs; [
      fuse
      fuse3
    ];
    serviceConfig.ExecStart = "${mountMedia}/bin/mount-media --syslog";
  };

  systemd.tmpfiles.rules = [
    "d /caches - root root"
    "d /caches/media - jellyfin jellyfin"

    "d /Media - jellyfin jellyfin"

    "d /root/.config - root root"
    "d /root/.config/rclone - root root"
    "L /root/.config/rclone/rclone.conf - - - - ${secrets.rclone_config.path}"
  ];
}
