{
  config,
  lib,
  pkgs,
  ...
}: {
  imports = [../../../agenix/age/identityPaths];

  options.dotfiles.inputs.home-manager.programs.borgmatic.enable =
    lib.dotfiles.mkEnableOption;

  config =
    lib.mkIf
    config.dotfiles.inputs.home-manager.programs.borgmatic.enable
    {
      age.secrets.modulesHomeManagerProgramsBorgmaticEncryptionPasscommand = {
        file = ./encryption_passcommand.age;
      };

      dotfiles.inputs.agenix.age.identityPaths.enable = true;

      programs.borgmatic = {
        backups.home = {
          consistency.checks = let
            monthly = "1 month";
            weekly = "1 week";
          in [
            {
              name = "archives";
              frequency = weekly;
            }

            {
              name = "data";
              frequency = monthly;
            }

            {
              name = "extract";
              frequency = monthly;
            }

            {
              name = "repository";
              frequency = weekly;
            }
          ];

          hooks.extraConfig.before_backup = let
            ls = lib.getExe' pkgs.coreutils "ls";

            repository = let
              label = "home";
            in
              (
                lib.lists.findFirst
                (repository: repository ? label && repository.label == label)
                (throw "undefined repository: ${label}")
                config.programs.borgmatic.backups.home.location.repositories
              )
              .path;
          in
            # The special exit status of 75 results in a soft failure:
            #
            # > Zero is success; anything else other than 75 is an error
            # >
            # > -- https://torsion.org/borgmatic/docs/how-to/backup-to-a-removable-drive-or-an-intermittent-server/
            [''${ls} "${repository}" >/dev/null || exit 75''];

          location = {
            excludeHomeManagerSymlinks = true;

            repositories = [
              {
                label = "home";
                path = "/tmp/${config.home.username}/borgbackup";
              }
            ];

            sourceDirectories = [config.home.homeDirectory];
          };

          retention = {
            keepDaily = 7;
            keepHourly = 24;
            keepMinutely = 60;
            keepMonthly = 6;
            keepSecondly = 60;
            keepWeekly = 5;
            keepWithin = "2d";
            keepYearly = 1;
          };

          storage.encryptionPasscommand = "${
            pkgs.runtimeShell
          } -c '${
            lib.getExe' pkgs.coreutils "cat"
          } \"${
            config.age.secrets.modulesHomeManagerProgramsBorgmaticEncryptionPasscommand.path
          }\"'";
        };

        enable = true;
      };
    };
}
