aboutsummaryrefslogtreecommitdiff
path: root/hosts/enode/impermenance.nix
blob: c15ea85a5075a5e2d8703a132b2896721e3fea06 (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
{ utils, ... }: {
  # Use /persist as the persistence root, matching Disko's mountpoint
  environment.persistence."/persist" = {
    hideMounts = true;
    directories = [
      "/var/lib/nixos"
      "/var/lib/systemd/coredump"
      "/var/lib/systemd/timers"

      "/var/lib/backups"
      "/var/lib/headscale"
      "/var/lib/caddy" # for certs
      {
        directory = "/var/lib/secrets";
        user = "root";
        group = "root";
        mode = "u=rwx,g=,o=";
      }
    ];
    files = [
      "/etc/machine-id"
      "/etc/shadow"
      "/etc/passwd"
    ];
  };

  boot.initrd.systemd.services.wipe-root = {
    # Specify dependencies explicitly
    unitConfig.DefaultDependencies = false;
    serviceConfig.Type = "oneshot";
    wantedBy = [ "initrd.target" ];
    before = [ "sysroot.mount" ]; # before any fs are mounted

    # Wait for the disk to appear
    requires = [
      "${utils.escapeSystemPath "/dev/disk/by-label/root"}.device"
    ];
    after = [
      "${utils.escapeSystemPath "/dev/disk/by-label/root"}.device"
      # Allow hibernation to resume before trying to alter any data
      "local-fs-pre.target"
    ];

    script = ''
      mkdir /btrfs_tmp
      mount /dev/disk/by-label/root /btrfs_tmp
      trap 'umount /btrfs_tmp' EXIT
      if [ -e /btrfs_tmp/root ]; then
        mkdir -p /btrfs_tmp/old_roots
        timestamp="$(date --date="@$(stat -c %Y /btrfs_tmp/root)" "+%Y-%m-%-d_%H:%M:%S")"
        mv /btrfs_tmp/root "/btrfs_tmp/old_roots/$timestamp"
      fi

      find /btrfs_tmp/old_roots/ -maxdepth 1 -mtime +30 -print0 |
        xargs --null -I '{}' btrfs subvolume delete --recursive '{}'

      btrfs subvolume create /btrfs_tmp/root
    '';
  };
}