{ lib, config, ... }:

let
  cfg = config.diskLayout;
in
{
  options.diskLayout = {
    mainDiskDevice = lib.mkOption {
      type = lib.types.str;
      description = "The device ID for the main disk";
    };
    keyDiskDevice = lib.mkOption {
      type = lib.types.str;
      description = "The device ID for the key disk";
    };
  };

  config = {
    disko.devices = {
      disk.main = {
        device = cfg.mainDiskDevice;
        type = "disk";
        content = {
          type = "gpt";
          partitions = {
            esp = {
              name = "ESP";
              size = "512M";
              type = "EF00";
              content = {
                type = "filesystem";
                format = "vfat";
                mountpoint = "/boot";
                mountOptions = [
                  "umask=0077" # to avoid the random seed being world readable
                ];
              };
            };
            luksroot = {
              end = "-8G";
              content = {
                type = "luks";
                name = "luksroot";
                settings = {
                  allowDiscards = true;
                  keyFile = cfg.keyDiskDevice;
                  keyFileSize = 4096;
                };
                content = {
                  type = "btrfs";
                  subvolumes = {
                    "root" = {
                      mountpoint = "/";
                      mountOptions = [
                        "compress=zstd"
                        "noatime"
                      ];
                    };
                    "nix" = {
                      mountpoint = "/nix";
                      mountOptions = [
                        "compress=zstd"
                        "noatime"
                      ];
                    };
                    "persist" = {
                      mountpoint = "/persist";
                      mountOptions = [
                        "compress=zstd"
                        "noatime"
                      ];
                    };
                    "log" = {
                      mountpoint = "/var/log";
                      mountOptions = [
                        "compress=zstd"
                        "noatime"
                      ];
                    };
                  };
                };
              };
            };
            swap = {
              size = "8G";
              content = {
                type = "swap";
                randomEncryption = true;
              };
            };
          };
        };
      };
    };
  };
}
