{ lib, config, options, pkgs, modulesPath, ... }:
with lib;
let
  cfg = config.yoda.btrbkSnapshots;
  hourly = {
    preserve-min = "2d";
    preserve = "24h 7d 4w 6m";
  };
in
{
  options = {
    yoda.btrbkSnapshots = mkOption {
      type = types.listOf types.attrs;
      default = [];
      example = [{
        instance = "local-snapshot-ssd";
        # Optional.
        # Can be used to disable timer.
        #enable = false;
        volume = "/jc-data";
        snapshot_dir = "/snap";
        subvolume = {
          "arch.p1st.de" = {};
        };
      }];
      description = ''
        List containing attrsets.
        Each attrset is used to create one btrbk instance.
      '';
    };
  };

  # lib.forEach:
  #   https://github.com/NixOS/nixpkgs/blob/54f00576aa6139a9d54062d0edc2fb31423f0ffb/lib/lists.nix#L36
  # lib.attrsets.mergeAttrsList:
  #   https://github.com/NixOS/nixpkgs/blob/54f00576aa6139a9d54062d0edc2fb31423f0ffb/lib/attrsets.nix#L786
  config = {
    services.btrbk.instances =
      # Merge list of attr sets into one attr set.
      attrsets.mergeAttrsList (
        forEach
        cfg
        (x:
          # `services.btrbk.instances` template.
          {
            "${x.instance}" = {
              onCalendar = if (x.enable or true) then "hourly" else null;
              settings = {
                timestamp_format = "long";

                snapshot_preserve_min = hourly.preserve-min;
                snapshot_preserve = hourly.preserve;

                volume."${x.volume}" = {
                  snapshot_dir = x.snapshot_dir;
                  subvolume = x.subvolume;
                };
              };
            };
          }
        )
      );
  };
}
