{
  config,
  lib,
  pkgs,
  ...
}:
{

  imports = [
    ./updater.nix
    ./builder.nix
    ./veritysetup.nix
  ];

  system.build.updatePackage = pkgs.runCommand "update-package" { } ''
    mkdir "$out"
    cd "$out"
    cp "${config.system.build.image}"/* .
    ${pkgs.coreutils}/bin/sha256sum * > SHA256SUMS
  '';

  systemd.repart.partitions = {
    "10-esp" = {
      Type = "esp";
      UUID = "c12a7328-f81f-11d2-ba4b-00a0c93ec93b"; # Well known
      Format = "vfat";
      SizeMinBytes = "96M";
      SizeMaxBytes = "96M";
    };
    "20-root-verity-a" = {
      Type = "root-verity";
      SizeMinBytes = "64M";
      SizeMaxBytes = "64M";
    };
    "22-root-a" = {
      Type = "root";
      SizeMinBytes = "512M";
      SizeMaxBytes = "512M";
    };
    "30-root-verity-b" = {
      Type = "root-verity";
      SizeMinBytes = "64M";
      SizeMaxBytes = "64M";
      Label = "_empty";
      ReadOnly = 1;
    };
    "32-root-b" = {
      Type = "root";
      SizeMinBytes = "512M";
      SizeMaxBytes = "512M";
      Label = "_empty";
      ReadOnly = 1;
    };
    "40-var" = {
      Type = "var";
      UUID = "4d21b016-b534-45c2-a9fb-5c16e091fd2d"; # Well known
      Format = "btrfs";
      Label = "patos-state";
      Minimize = "off";
      FactoryReset = "yes";
      Encrypt = "tpm2";
      SizeMinBytes = "2G";
      SplitName = "-";
    };
  };

  boot.loader.grub.enable = false;
  boot.loader.efi.canTouchEfiVariables = true;
  boot.loader.systemd-boot.enable = true;
  boot.uki.name = "patos";

  boot.initrd = {
    compressor = "zstd";
    compressorArgs = [ "-8" ];

    luks.forceLuksSupportInInitrd = true;
    kernelModules = [
      "dm_mod"
      "dm_crypt"
    ] ++ config.boot.initrd.luks.cryptoModules;

    supportedFilesystems = {
      btrfs = true;
      erofs = true;
    };

    systemd.enable = true;
    systemd.repart.enable = true;
    systemd.services.systemd-repart = {
      after = lib.mkForce [ "sysroot.mount" ];
      requires = [ "sysroot.mount" ];
      serviceConfig.Environment = [
        "SYSTEMD_REPART_MKFS_OPTIONS_BTRFS=--nodiscard"
      ];
    };
  };

  system.etc.overlay.mutable = false;
  users.mutableUsers = false;

  boot.kernelParams = [
    "rootfstype=erofs"
    "rootflags=ro"
    "roothash=${config.system.build.verityRootHash}"
  ];

  fileSystems =
    let
      parts = config.systemd.repart.partitions;
    in
    {
      "/var" = {
        fsType = parts."40-var".Format;
        device = "/dev/mapper/var";
        encrypted = {
          enable = true;
          blkDev = "/dev/disk/by-partuuid/${parts."40-var".UUID}";
          label = "var";
        };
      };
    };

  # Required to mount the efi partition
  boot.kernelModules = [
    "vfat"
    "nls_cp437"
    "nls_iso8859-1"
  ];

  environment.etc."machine-id" = {
    text = "";
    mode = "0755";
  };

  # Refuse to boot on mount failure
  systemd.targets."sysinit".requires = [ "local-fs.target" ];
}