blob: 9dc3f1f80c16dc74deb78baf7806387849125560 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
  | 
{ config, lib, pkgs, ... }:
with lib;
let
  cfg = config.services.btrfs-snapshots;
  snapshotMount = str: "${cfg.mountPoint}/${cfg.mountPrefix}${str}";
in {
  options = {
    services.btrfs-snapshots = {
      enable = mkEnableOption "a systemd unit for btrfs snapshots";   
      mountPoint = mkOption {
        readOnly = true;
        type = types.path;
        default = "/mnt";
      };
      mountPrefix = mkOption {
        readOnly = true;
        type = types.str;
        default = "snapshot-";
      };
      readOnly = mkOption {
        type = types.bool;
        default = true;
      };
      persist = mkOption {
        type = types.bool;
        default = false;
      };
    };
  };
  
  config = mkIf cfg.enable {
    system.activationScripts."btrfs-snapshots" = ''
      mkdir -p ${mountPoint}
    '';
    systemd.services."btrfs-snapshot@" = {
      enable = true;
      unitConfig = {
        AssertPathIsDirectory = cfg.mountPoint;
        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"}";
      };
    };
  };
}
 
  |