Files
nix/modules/system/backups.nix.bak

103 lines
2.9 KiB
Nix

{ 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 = {
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";
EnvironmentFile = config.modules.system.backups.passphraseFile;
# 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 "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 lzma,9 \
"$BORG_REPO::${toString config.networking.hostName}-$timestamp" \
${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 "$timestamp - backup completed successfully."
'';
};
};
# 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 [ <path> ];