{ host, rpi4, experimental-users ? false }:

{ config, pkgs, ... }:
let
  artiq = builtins.getFlake git+https://github.com/m-labs/artiq.git;
in
{
  deployment.targetHost = host;
  deployment.hasFastConnection = true;
  nix.nixPath = [ "nixpkgs=${pkgs.path}" ];
  programs.command-not-found.dbPath = "${pkgs.path}/programs.sqlite";
  nixpkgs.system = "aarch64-linux";

  boot.loader.grub.enable = false;
  boot.loader.generic-extlinux-compatible.enable = true;
  boot.kernelParams = if rpi4 then ["cma=64M"] else []; # work around https://github.com/raspberrypi/linux/issues/3208
  boot.initrd.includeDefaultModules = false;

  fileSystems = {
    "/" = {
      device = "/dev/disk/by-label/NIXOS_SD";
      fsType = "ext4";
    };
  };

  services.openssh.enable = true;
  services.openssh.passwordAuthentication = false;
  services.openssh.gatewayPorts = "clientspecified";
  services.openssh.extraConfig =
    ''
    StreamLocalBindUnlink yes
    '';
  programs.mosh.enable = true;

  networking.hostName = host;

  networking.firewall.allowedTCPPorts = if host == "rpi-2" then [ 6000 ] else [];

  time.timeZone = "Asia/Hong_Kong";

  users.extraGroups.plugdev = { };
  users.mutableUsers = false;
  users.defaultUserShell = pkgs.fish;
  users.extraUsers = (import ./common-users.nix { inherit pkgs; }) //
    (pkgs.lib.optionalAttrs experimental-users (import ./experimental-users.nix { inherit pkgs; })) // {
    nixbld = {
      isNormalUser = true;
      extraGroups = ["plugdev" "dialout"];
      openssh.authorizedKeys.keys = [
        "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIGJGICdNM9mHHAa1Cxk9Wz3YLkIEeqrIQGxM0aoy1g5O"
      ];
    };
  };
  security.sudo.wheelNeedsPassword = false;
  services.udev.packages = [ artiq.packages.aarch64-linux.openocd-bscanspi ];
  services.udev.extraRules = (import ./extra-udev.nix);

  documentation.enable = false;
  environment.systemPackages = with pkgs; [
    psmisc wget vim git sshfs usbutils uhubctl lm_sensors file mosh tmux
    artiq.packages.aarch64-linux.openocd-bscanspi
    xc3sprog
    screen gdb minicom picocom
  ];
  programs.fish.enable = true;
  programs.wireshark.enable = true;

  nix.settings.trusted-public-keys = ["nixbld.m-labs.hk-1:5aSRVA5b320xbNvu30tqxVPXpld73bhtOeH6uAjRyHc="];
  nix.settings.substituters = ["https://nixbld.m-labs.hk" "https://cache.nixos.org"];
  nix.settings.trusted-users = ["root" "sb"];

  nix.extraOptions = ''
    experimental-features = nix-command flakes impure-derivations
  '';
}