# Nomarchy installer disk layout — single disk, GPT, 1 GiB ESP, BTRFS
# root with subvolumes, optionally under LUKS2. Invoked by
# nomarchy-install via:
#
#   disko --mode destroy,format,mount \
#         --argstr mainDrive /dev/nvme0n1 \
#         --arg    withLuks true \
#         --argstr swapSize 16G \
#         disko-config.nix
#
# Ported from the previous iteration's golden-path config (multi-disk
# RAID and the impermanence snapshot dropped for v1 — see git history
# of installer/disko-config.nix at 3bdfc35 when adding them back).
# Function arguments, not sed-templating: escaping shell into Nix
# proved fragile twice before.
{ mainDrive
, withLuks ? true
, swapSize ? "0"   # "0" or "0G" = no swap; otherwise e.g. "16G" (hibernation-sized)
, ...
}:

let
  btrfsMountOptions = [ "compress=zstd" "noatime" ];
  # Installer historically always appended "G"; accept both "0" and "0G".
  noSwap = swapSize == "0" || swapSize == "0G";

  rootBtrfs = {
    type = "btrfs";
    extraArgs = [ "-f" ];
    subvolumes = {
      "@" = { mountpoint = "/"; mountOptions = btrfsMountOptions; };
      "@home" = { mountpoint = "/home"; mountOptions = btrfsMountOptions; };
      "@nix" = { mountpoint = "/nix"; mountOptions = btrfsMountOptions; };
      "@log" = { mountpoint = "/var/log"; mountOptions = btrfsMountOptions; };
      # snapper timeline snapshots (nomarchy.system.snapper.enable)
      "@snapshots" = { mountpoint = "/.snapshots"; mountOptions = btrfsMountOptions; };
    } // (if noSwap then { } else {
      # Hibernation-ready swapfile on its own subvolume; disko's
      # mkswapfile handles the BTRFS NOCOW requirements.
      "@swap" = {
        mountpoint = "/swap";
        swap.swapfile.size = swapSize;
      };
    });
  };
in
{
  disko.devices.disk.main = {
    type = "disk";
    device = mainDrive;
    content = {
      type = "gpt";
      partitions = {
        # 1 GiB ESP — fits several kernel generations + initrd.
        ESP = {
          priority = 1;
          name = "ESP";
          start = "1M";
          end = "1G";
          type = "EF00";
          content = {
            type = "filesystem";
            format = "vfat";
            mountpoint = "/boot";
            mountOptions = [ "umask=0077" ];
          };
        };
        root = {
          size = "100%";
          content =
            if withLuks then {
              type = "luks";
              name = "crypted";
              passwordFile = "/tmp/nomarchy-luks.key";
              settings.allowDiscards = true;
              content = rootBtrfs;
            } else
              rootBtrfs;
        };
      };
    };
  };
}
