impermanence.nix 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. { config
  2. , inputs
  3. , lib
  4. , ...
  5. }:
  6. {
  7. imports = [
  8. inputs.impermanence.nixosModules.impermanence
  9. ];
  10. boot.initrd.postDeviceCommands = lib.mkAfter ''
  11. #!/bin/sh
  12. DEVICE=${config.disko.devices.disk.main.device}-part2
  13. # Mount Btrfs root
  14. mkdir -p /mnt
  15. if ! mount -o subvol=/ $DEVICE /mnt; then
  16. echo "Failed to mount $DEVICE at /mnt"
  17. exit 1
  18. fi
  19. # Create directory for old roots
  20. mkdir -p /mnt/old-roots
  21. # Move current root to old-roots with current timestamp
  22. if [[ -e /mnt/@root ]]; then
  23. timestamp=$(date +%Y-%m-%d_%H:%M:%S)
  24. if ! btrfs subvolume snapshot -r /mnt/@root "/mnt/old-roots/@root-$timestamp"; then
  25. echo "Failed to move /mnt/@root to old-roots"
  26. umount /mnt
  27. exit 1
  28. fi
  29. fi
  30. # Function to recursively delete subvolumes
  31. delete_subvolume_recursively() {
  32. for i in $(btrfs subvolume list -o "$1" | cut -f 9- -d ' '); do
  33. delete_subvolume_recursively "/mnt/$i"
  34. done
  35. if ! btrfs subvolume delete "$1"; then
  36. echo "Failed to delete subvolume $1"
  37. fi
  38. }
  39. # Delete old roots more than 5
  40. index=0
  41. for i in $(btrfs subvolume list /mnt | grep 'old-roots/@root-' | cut -f 9- -d ' ' | sort -r); do
  42. if [[ $index -ge 5 ]]; then
  43. delete_subvolume_recursively "/mnt/$i"
  44. fi
  45. index=$((index + 1))
  46. done
  47. # Create or restore fresh root
  48. if [[ -e /mnt/@root-blank ]]; then
  49. delete_subvolume_recursively /mnt/@root
  50. if ! btrfs subvolume snapshot /mnt/@root-blank /mnt/@root; then
  51. echo "Failed to snapshot @root-blank to @root"
  52. umount /mnt
  53. exit 1
  54. fi
  55. else
  56. if ! btrfs subvolume create /mnt/@root-blank; then
  57. echo "Failed to create @root-blank"
  58. umount /mnt
  59. exit 1
  60. fi
  61. if ! btrfs subvolume create /mnt/@root; then
  62. echo "Failed to create @root"
  63. umount /mnt
  64. exit 1
  65. fi
  66. fi
  67. # Unmount
  68. if ! umount /mnt; then
  69. echo "Failed to unmount /mnt"
  70. exit 1
  71. fi
  72. '';
  73. # Persistent directories for impermanence
  74. fileSystems."/persist".neededForBoot = true;
  75. fileSystems."/var/lib".neededForBoot = true;
  76. environment.persistence."/persist" = {
  77. hideMounts = true;
  78. directories = [
  79. "/etc/ssh"
  80. "/var/cache"
  81. ];
  82. files = [
  83. "/etc/machine-id"
  84. ];
  85. users.thomas.directories = [
  86. ".ssh"
  87. ".local/share"
  88. ];
  89. };
  90. }