{ pkgs
, lib
, config
, ... }: with lib; let
  cfg = config.global.libvirt;
in {
  options.global.libvirt = {
    enable = mkEnableOption "libvirt virtualisation daemon" // { default = true; };
  };

  config = mkIf cfg.enable {
    virtualisation.libvirtd = {
      enable = true;
      qemu.runAsRoot = false;
      qemu.swtpm.enable = true;

      # disable as much implicit state as possible
      onBoot = "ignore";
      onShutdown = "shutdown";
      parallelShutdown = 5;
    };

    environment.systemPackages = with pkgs; [ virtiofsd ];

    # USB redirection requires a setuid wrapper
    virtualisation.spiceUSBRedirection.enable = true;

    environment.persistence."/nix/persist/fhs".directories = [
      "/var/lib/libvirt"
    ];
    global.fs.zfs.mountpoints."/nix/persist/service/libvirt" = "service/libvirt";

    # allow management by admin users
    users.adminGroups = [ "libvirtd" ];
  };
}
