# { pkgs, lib, ... }:
# let
#   uefi_pi4 = pkgs.callPackage ./pi4-uefi.nix { };
# in
# {
#   boot = {
#     loader = {
#         systemd-boot.enable = lib.mkForce false;
#         efi.canTouchEfiVariables = false;
#         generic-extlinux-compatible.enable = lib.mkForce true;
#     };
#     plymouth.enable = false;
#     kernelPackages = pkgs.linuxPackages_rpi4;
#     kernelModules = [ "i2c-dev" "i2c-bcm2835" ];
#     initrd.kernelModules = [  "i2c-dev" "i2c-bcm2835"  ];
#   };
#   # environment.systemPackages = [ uefi_pi4 ];

#   # Copy UEFI firmware files to the boot partition
#   # system.activationScripts.installUEFIFirmware.text = ''
#   #   cp -r ${uefi_pi4}/share/uefi_rpi4/* /boot/firmware/
#   # '';
# }
{
  config,
  pkgs,
  lib,
  ...
}:
let
  kernelBundle = pkgs.linuxAndFirmware.latest;
in
{
  system.nixos.tags =
    let
      cfg = config.boot.loader.raspberry-pi;
    in
    [
      "raspberry-pi-${cfg.variant}"
      cfg.bootloader
      config.boot.kernelPackages.kernel.version
    ];

  boot = lib.mkForce {
    loader.raspberry-pi = {
      firmwarePackage = kernelBundle.raspberrypifw;
      variant = "4";
    };
    kernelPackages = kernelBundle.linuxPackages_rpi4;
  };

  hardware.raspberry-pi.config = {
    all = {
      # [all] conditional filter, https://www.raspberrypi.com/documentation/computers/config_txt.html#conditional-filters

      base-dt-params = {
        i2c_arm = {
          enable = true;
          value = "on";
        };
        i2c = {
          enable = true;
          value = "on";
        };
        spi = {
          enable = true;
          value = "on";
        };
      };

      options = {
        # https://www.raspberrypi.com/documentation/computers/config_txt.html#enable_uart
        # in conjunction with `console=serial0,115200` in kernel command line (`cmdline.txt`)
        # creates a serial console, accessible using GPIOs 14 and 15 (pins
        #  8 and 10 on the 40-pin header)
        enable_uart = {
          enable = true;
          value = true;
        };
        # https://www.raspberrypi.com/documentation/computers/config_txt.html#uart_2ndstage
        # enable debug logging to the UART, also automatically enables
        # UART logging in `start.elf`
        uart_2ndstage = {
          enable = true;
          value = true;
        };
      };

      # Base DTB parameters
      # https://github.com/raspberrypi/linux/blob/a1d3defcca200077e1e382fe049ca613d16efd2b/arch/arm/boot/dts/overlays/README#L132
      base-dt-params = {

      };

    };
  };
}
