# ISO does not work with systemd initrd yet https://github.com/NixOS/nixpkgs/pull/291750
{
  config,
  lib,
  pkgs,
  ...
}:

{
  imports = [ ];

  options = {
    me.secureBoot = {
      enable = lib.mkOption {
        default = false;
        type = lib.types.bool;
        description = ''
          Enable to use secure boot.
        '';
      };
    };
  };

  config = lib.mkMerge [
    {
      environment.systemPackages = with pkgs; [
        tpm2-tools # For tpm2_eventlog to check for OptionRoms
        # cp /sys/kernel/security/tpm0/binary_bios_measurements eventlog
        # tpm2_eventlog eventlog | grep "BOOT_SERVICES_DRIVER"
        sbctl # For debugging and troubleshooting Secure Boot.
      ];
    }
    (lib.mkIf (!config.me.buildingIso) {

      boot.loader.grub.enable = false;
      # Use the systemd-boot EFI boot loader.
      boot.loader.systemd-boot.enable = true;
      # TODO: make not write bootx64.efi
      boot.loader.efi.canTouchEfiVariables = false;

      # Automatically delete old generations
      boot.loader.systemd-boot.configurationLimit = 3;

      boot.loader.systemd-boot.memtest86.enable = true;

      # Check what will be lost with `zfs diff zroot/linux/root@blank`
      boot.initrd.systemd.enable = lib.mkDefault true;
      boot.initrd.systemd.services.zfs-rollback = {
        description = "Rollback ZFS root dataset to blank snapshot";
        wantedBy = [
          "initrd.target"
        ];
        after = [
          "zfs-import-zroot.service"
        ];
        before = [
          "sysroot.mount"
        ];
        path = with pkgs; [
          zfs
        ];
        unitConfig.DefaultDependencies = "no";
        serviceConfig.Type = "oneshot";
        script = ''
          zfs rollback -r zroot/linux/nix/root@blank
          zfs rollback -r zroot/linux/nix/home@blank
          echo "rollback complete"
        '';
      };

      # boot.loader.systemd-boot.extraEntries = {
      #   "windows.conf" = ''
      #     title Windows
      #     efi /EFI/Microsoft/Boot/bootmgfw.efi
      #     options root=PARTUUID=17e325bf-a378-4d1d-be6a-f6df5476f0fa
      #   '';
      # };
      environment.persistence."/persist" = lib.mkIf (!config.me.buildingIso) {
        hideMounts = true;
        directories = [
          "/var/lib/sbctl" # Secure Boot Keys
        ];
      };
    })
    (lib.mkIf (config.me.secureBoot.enable) {
      environment.systemPackages = with pkgs; [
        sbctl
      ];
      boot.loader.systemd-boot.enable = lib.mkForce false;
      boot.lanzaboote = {
        enable = true;
        pkiBundle = "/var/lib/sbctl";
      };
    })
  ];
}
# efibootmgr -c -d /dev/sda -p 1 -L NixOS-boot -l '\EFI\NixOS-boot\grubx64.efi'

# Text-only:
# sudo cp "$(nix-build '<nixpkgs>' --no-out-link -A 'refind')/share/refind/refind_x64.efi" /boot/EFI/boot/bootx64.efi

# Full graphics:
# $ sudo nix-shell -p refind efibootmgr
# $ refind-install