{ config, lib, pkgs, ... }: with lib; let cfg = config.services.btrfs-snapshots; snapshotMount = str: "${str}${cfg.mountSuffix}"; in { options = { services.btrfs-snapshots = { enable = mkEnableOption "a systemd unit for btrfs snapshots"; mountSuffix = mkOption { type = types.str; default = ".snapshot"; }; readOnly = mkOption { type = types.bool; default = true; }; persist = mkOption { type = types.bool; default = false; }; }; }; config = mkIf cfg.enable { systemd.services."btrfs-snapshot@" = { enable = true; unitConfig = { StopWhenUnneeded = !cfg.persist; }; serviceConfig = with pkgs; { Type = "oneshot"; ExecStartPre = "-${btrfs-progs}/bin/btrfs subvolume delete -c ${snapshotMount "%i"}"; ExecStart = "${btrfs-progs}/bin/btrfs subvolume snapshot ${optionalString cfg.readOnly "-r"} %f ${snapshotMount "%i"}"; RemainAfterExit = true; ExecStop = "${btrfs-progs}/bin/btrfs subvolume delete -c ${snapshotMount "%i"}"; }; }; }; }