{ lib, config, pkgs, ... }: let cfg = config.services.backup; in { # Configuration options.services.backup = { enable = lib.mkEnableOption "Whether to enable backups or not."; source = lib.mkOption { type = lib.types.path; default = null; description = "The path to save."; }; dest = lib.mkOption { type = lib.types.either lib.types.path lib.types.str; default = null; description = "A destination for the backup."; }; compression = { command = lib.mkOption { type = lib.types.nullOr lib.types.str; default = "tar -caf \"$DST\" \"$SRC\""; description = "A bash command to compress backups. Defaults to an uncompressed tar archive."; }; }; encryption = { command = lib.mkOption { type = lib.types.str; description = "A bash command to encrypt backups. Defaults to a clear archive (simple cat)."; default = "cat \"$SRC\" > \"$DST\""; }; key = lib.mkOption { type = lib.types.nullOr lib.types.path; description = "A key to encrypt backups."; default = null; }; }; salvation = { command = lib.mkOption { type = lib.types.str; description = "A bash command to save the archive. Defaults to a copy from source to dest."; default = "cp \"$SRC\" \"$DST\""; }; }; }; # Implementation config = let script = pkgs.writeShellApplication { name = "backup.sh"; runtimeInputs = [ pkgs.gnutar pkgs.gzip ]; text = '' #!/bin/bash # Archive creation and compression SRC=${cfg.source} DST=$(mktemp --suffix=.tar) echo "Archiving and compressing $SRC to $DST." ${cfg.compression.command} # Archive encryption (optionnal) SRC=$DST DST=$(mktemp --suffix=.tar.encrypted) echo "Encyphering $SRC to $DST." ${cfg.encryption.command} # Archive salvation SRC=$DST DST="${cfg.dest}/${baseNameOf cfg.source}.tar.enc" echo "Saving $SRC to $DST." ${cfg.salvation.command} ''; }; in lib.mkIf cfg.enable { systemd.timers.backup = { wantedBy = [ "timers.target" ]; timerConfig = { OnBootSec = "5m"; OnCalendar = "* *-*-* 00:00:00"; Unit = "backup.service"; Persistent = true; }; }; systemd.services.backup = { enable = cfg.enable; after = [ "network-online.target" ]; wants = [ "network-online.target" ]; description = "Saves a directory and its content."; serviceConfig = { Type = "simple"; ExecStart = "${script}/bin/backup.sh"; }; }; }; }