# Shared media group, directory layout, and Jellyfin config bind-mount on /mnt/media-stack.
{ config, lib, pkgs, ... }:
let
  paths = import ./media-stack-paths.nix;
  prowlarrCustomIndexer = "${./../_services/prowlarr/torrent9-custom.yml}";
  inherit (paths)
    mediaRoot
    downloadsDir
    downloadsIncompleteDir
    sonarrDataDir
    radarrDataDir
    prowlarrDataDir
    qbittorrentDataDir
    seerrConfigDir
    dispatcharrDataDir
    organizrDataDir
    jellyfinConfigDir
    jellyfinMoviesDir
    jellyfinTvDir
    ;
in
{
  _module.args.mediaStackPaths = paths;

  users.groups.media = { };

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

  # Layout dirs only after /mnt/media-stack is mounted (tmpfiles at early boot would
  # otherwise create paths on the root fs and break bind mounts / boot).
  systemd.services.r5500-media-stack-dirs = {
    description = "Create media-stack directory layout";
    after = [ "mnt-media\\x2dmedia\\x2dstack.mount" ];
    wantedBy = [ "multi-user.target" ];
    serviceConfig = {
      Type = "oneshot";
      RemainAfterExit = true;
    };
    script = ''
      set -e
      install -d -m 0775 -o root -g media ${mediaRoot}
      install -d -m 2775 -o root -g media ${jellyfinMoviesDir} ${jellyfinTvDir} ${downloadsDir}
      install -d -m 2775 -o root -g media ${downloadsIncompleteDir}
      install -d -m 0755 -o jellyfin -g jellyfin ${jellyfinConfigDir}
      install -d -m 0700 -o sonarr -g sonarr ${sonarrDataDir}
      install -d -m 0700 -o radarr -g radarr ${radarrDataDir}
      install -d -m 0700 -o prowlarr -g prowlarr ${prowlarrDataDir}
      install -d -m 0750 -o qbittorrent -g qbittorrent ${qbittorrentDataDir}
      install -d -m 0755 -o jellyseerr -g jellyseerr ${seerrConfigDir} 2>/dev/null \
        || install -d -m 0755 -o root -g root ${seerrConfigDir}
      install -d -m 0777 -o root -g root ${dispatcharrDataDir}
      install -d -m 0755 -o organizr -g organizr ${organizrDataDir} 2>/dev/null \
        || install -d -m 0755 -o root -g root ${organizrDataDir}
      install -d -m 0700 -o prowlarr -g prowlarr ${prowlarrDataDir}/Definitions/Custom
      ln -sfn ${prowlarrCustomIndexer} ${prowlarrDataDir}/Definitions/Custom/torrent9-custom.yml
    '';
  };

  # Jellyfin metadata on the media subvolume; nofail so a missing subvol never bricks boot.
  fileSystems."/var/lib/jellyfin" = {
    device = jellyfinConfigDir;
    fsType = "none";
    neededForBoot = false;
    options = [
      "bind"
      "nofail"
      "x-systemd.after=mnt-media\\x2dmedia\\x2dstack.mount"
    ];
  };
}
