{ 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; in { options.modules.system.backups = { 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 (backup_paths != []) { systemd.services.borg-backup = { description = "BorgBackup service for system data"; serviceConfig = { Type = "oneshot"; EnvironmentFile = config.modules.system.backups.passphraseFile; ExecStart = pkgs.writeShellScript "borg-backup" '' set -euo pipefail export BORG_PASSPHRASE="$(cat ${passwd_file})" export BORG_REPO="${cfg.repo}" # Initialize repo if it doesn't exist if ! borg info "$BORG_REPO" >/dev/null 2>&1; then echo "init borg repo at $BORG_REPO" borg init --encryption=repokey "$BORG_REPO" fi # Create backup echo "starting backup..." borg create \ --verbose \ --filter AME \ --list \ --stats \ --show-rc \ --compression lz4 \ "$BORG_REPO::$(hostname)-$(date +'%Y-%m-%dT%H:%M:%S')" \ ${lib.concatStringsSep " " cfg.paths} # Prune old backups according to retention policy echo "Pruning old backups..." borg prune -v --list "$BORG_REPO" \ --keep-daily=7 \ --keep-weekly=52 \ --keep-monthly=-1 echo "Backup completed successfully." ''; }; }; systemd.timers.borg-backup = { description = "daily borg backup timer"; wantedBy = [ "timers.target" ]; timerConfig = { OnCalendar = "daily"; Persistent = true; }; }; environment.systemPackages = [ pkgs.borgbackup ]; }; } # add to modules # modules.system.backups.paths = lib.mkIf cfg.backups [ ];