# Media stack storage on r5500: btrfs subvolume @media-stack on the OS disk (sda4).
{ config, pkgs, lib, ... }:
let
  btrfsUuid = "934a5ec3-4bab-49c3-96c9-c857c50076ba";
  btrfsDevice = "/dev/disk/by-uuid/${btrfsUuid}";
  # Created under subvol=@ → full path is @/@media-stack (not a top-level @media-stack).
  mediaSubvol = "@/@media-stack";
in
{
  # Create @media-stack before /mnt/media-stack is mounted.
  systemd.services.r5500-media-stack-subvolume = {
    description = "Create btrfs subvolume @media-stack on sda4 if missing";
    before = [ "mnt-media\\x2dmedia\\x2dstack.mount" ];
    wantedBy = [ "local-fs-pre.target" ];
    serviceConfig = {
      Type = "oneshot";
      RemainAfterExit = true;
    };
    script = ''
      rootMount="/mnt/.r5500-btrfs-root"
      mkdir -p "$rootMount"
      if ! mountpoint -q "$rootMount"; then
        mount -o subvol=@ "${btrfsDevice}" "$rootMount"
        umountAfter=1
      else
        umountAfter=0
      fi
      if ! ${pkgs.btrfs-progs}/bin/btrfs subvolume show "$rootMount/@media-stack" >/dev/null 2>&1; then
        ${pkgs.btrfs-progs}/bin/btrfs subvolume create "$rootMount/@media-stack"
      fi
      if [ "$umountAfter" -eq 1 ]; then
        umount "$rootMount"
      fi
    '';
  };

  # Optional 1 TiB cap (run once after first boot if desired):
  #   sudo btrfs quota enable /mnt/media-stack && sudo btrfs qgroup limit 1T /mnt/media-stack

  fileSystems."/mnt/media-stack" = {
    device = btrfsDevice;
    fsType = "btrfs";
    neededForBoot = false;
    options = [
      "subvol=${mediaSubvol}"
      "compress=zstd"
      "noatime"
      "nofail"
      "x-systemd.device-timeout=30"
    ];
  };
}
