{ config, lib, pkgs, ... }: let cfg = config.modules.system.backups; borg = "${pkgs.borgbackup}/bin/borg"; backup_paths = lib.unique config.modules.system.backups.paths; passwd_file = config.sops.secrets."borg_passwd".path; jobs = { sungger = { paths = [ "/var/lib/radarr" "/var/lib/sonarr" ]; }; hoass = { paths = [ "/var/lib/zigbee2mqtt" "/var/lib/hass" "/var/lib/mosquitto" ]; }; huh = { paths = [ "/home/blake/.nix" ]; }; }; in { options.modules.system.backups = { enable = lib.mkEnableOption "enables backups with borg"; paths = lib.mkOption { type = lib.types.listOf lib.types.path; default = []; description = "list of directories to back up"; }; repo = lib.mkOption { type = lib.types.path; default = "/holocron/borg"; description = "borg repository path"; }; passphraseFile = lib.mkOption { type = lib.types.path; default = passwd_file; description = "borg repository passphrase file"; }; }; config = lib.mkIf (cfg.enable && backup_paths != []) { # systemd.tmpfiles.rules = [ # "d ${cfg.repo} 0755 root root" # ]; systemd.services.backups = { description = "backup service with borg!"; path = [ pkgs.borgbackup ]; serviceConfig = { Type = "oneshot"; # the actual script borg is using ExecStart = pkgs.writeShellScript "borg-backup" '' set -euo pipefail export BORG_PASSPHRASE="$(cat ${passwd_file})" export BORG_REPO="${cfg.repo}" timestamp="$(date +'%Y-%m-%dT%H:%M:%S')" # Initialize repo if it doesn't exist if ! borg info "$BORG_REPO" >/dev/null 2>&1; then echo "Initializing Borg repo at $BORG_REPO" borg init --encryption=repokey "$BORG_REPO" fi echo "Starting backup run at $timestamp" # Loop over all jobs (attribute set keys) ${lib.concatStringsSep "\n\n" (lib.mapAttrsToList (jobName: jobCfg: '' echo "=== Backing up ${jobName} ===" archive="${jobName}-$timestamp" echo "Backing up paths: ${lib.concatStringsSep " " jobCfg.paths} → $archive" borg create \ --verbose \ --filter AME \ --list \ --stats \ --show-rc \ --compression lzma,9 \ "$BORG_REPO::$archive" \ ${lib.concatStringsSep " " jobCfg.paths} echo "Pruning old backups for ${jobName}..." borg prune -v --list "$BORG_REPO" \ --prefix "${jobName}-" \ --keep-daily=7 \ --keep-weekly=52 \ --keep-monthly=-1 '' ) jobs)} echo "Backup run complete at $timestamp." ''; }; }; # create timer to run backups daily systemd.timers.backups = { description = "daily borg backup timer"; wantedBy = [ "timers.target" ]; timerConfig = { OnCalendar = "daily"; Persistent = true; }; }; # install borg binary environment.systemPackages = [ pkgs.borgbackup ]; # declare secret for repo password sops.secrets = { "borg_passwd" = { owner = "root"; group = "root"; }; }; }; } # add to modules # modules.system.backups.paths = lib.mkIf cfg.backups [ ];