{ lib, pkgs, config, ... }: { # Configuration options.services.backup = lib.mkOption { type = lib.types.attrsOf ( lib.types.submodule ( { ... }: { options = { enable = lib.mkEnableOption "Whether to enable backups for this path or not."; 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\""; }; }; }; } ) ); }; config = let systemd_backups = map ( attrset: let script = pkgs.writeShellApplication { name = "backup-${baseNameOf attrset.name}.sh"; runtimeInputs = [ pkgs.gnutar pkgs.gzip ]; text = '' #!/bin/bash # Archive creation and compression SRC=${attrset.name} DST=$(mktemp --suffix=.tar) echo "Archiving and compressing $SRC to $DST." ${attrset.value.compression.command} # Archive encryption (optionnal) SRC=$DST DST=$(mktemp --suffix=.tar.encrypted) echo "Encyphering $SRC to $DST." ${attrset.value.encryption.command} # Archive salvation SRC=$DST DST="${attrset.value.dest}/${baseNameOf attrset.name}.tar.enc" echo "Saving $SRC to $DST." ${attrset.value.salvation.command} ''; }; in { timers."backup-${baseNameOf attrset.name}" = { wantedBy = [ "timers.target" ]; timerConfig = { OnBootSec = "5m"; OnCalendar = "* *-*-* 00:00:00"; Unit = "backup-${baseNameOf attrset.name}.service"; Persistent = true; }; }; services."backup-${baseNameOf attrset.name}" = { enable = attrset.value.enable; after = [ "network-online.target" ]; wants = [ "network-online.target" ]; description = "Saves a directory and its content."; serviceConfig = { Type = "simple"; ExecStart = "${script}/bin/backup-${baseNameOf attrset.name}.sh"; }; }; } ) (lib.attrsets.attrsToList config.services.backup); in { systemd = lib.attrsets.mergeAttrsList systemd_backups; }; }