# BTRFS mount options.
#
# compress=
#   `nixos-generate-config` does not detect mount options, so we add them here.
#   https://nixos.wiki/wiki/Btrfs#Compression
#
# noatime
#  Under read intensive work-loads, specifying noatime significantly improves performance because no new access time information needs to be written.
#  https://man.archlinux.org/man/btrfs.5#NOTES_ON_GENERIC_MOUNT_OPTIONS
#
# commit=
#   The number of seconds between periodic commits to the filesystem. This is 30 seconds by default. Increasing this value reduces the frequency of periodic writes which can reduce wear on the disk. However, this also increases the risk of data loss during the event of an untimely crash.
#   https://www.jwillikers.com/btrfs-mount-options
#


{ lib, config, options, pkgs, modulesPath, ... }:
with lib;
let
  cfg = config.yoda.btrfsMounts;
in
{
  options = {
    yoda.btrfsMounts = mkOption {
      type = types.listOf types.path;
      default = config.yoda.btrfsFileSystems;
      example = ["/" "/mnt/data"];
      description = ''
        List containing each BTRFS mountpoint.
        If each BTRFS filesystem is only mounted once, this can be left at its default value.
      '';
    };
  };

  config = mkIf (length cfg > 0) {
    # For each element (e.g. "/") in `cfg` create this config:
    #   fileSystems."/".options = [ "compress=zstd" "noatime" "commit=120" ];
    fileSystems = builtins.listToAttrs (builtins.map (btrfs_mount_path: {
      name = btrfs_mount_path;
      value = { options = [ "compress=zstd" "noatime" "commit=120" ]; }; # TODO lower this for Laptop with battery -> Power loss if empty. Or: Fix GNOME not suspending if battery below 8 percent!
    }) cfg);
  };
}
