# BTRFS scrub.
#
# Scrubbing is the process of checking file consistency.
# Scrubbing may be done "online", meaning you don't need to unmount a subvolume to scrub it.
# https://nixos.wiki/wiki/Btrfs#Scrubbing
# Btrfs scrub is "[a]n online filesystem checking tool. Reads all the data and metadata on the filesystem and uses checksums and the duplicate copies from RAID storage to identify and repair any corrupt data."
# https://wiki.archlinux.org/title/btrfs#Scrub
# The scrub command operates on a whole filesystem, not just individual subvolumes.
# https://unix.stackexchange.com/a/724412
#
# As this command reads all data, it wears down the disk. One should not run it too often. For large, slow disks once per month should be fine.
#
# To run it manually:
#   sudo btrfs scrub start /
#   sudo btrfs scrub status /

{ lib, config, options, pkgs, modulesPath, ... }:
with lib;
let
  cfg = config.yoda.btrfsFileSystems;
in
{
  options = {
    yoda.btrfsFileSystems = mkOption {
      type = types.listOf types.path;
      default = ["/"];
      example = ["/" "/mnt/data"];
      description = ''
        List containing each mounted BTRFS filesystem once.
      '';
    };
  };

  config = mkIf (length cfg > 0) {
    services.btrfs.autoScrub = {
      enable = true;
      interval = "monthly";
      fileSystems = cfg;
    };
  };
}
