{ config, lib, pkgs, ... }:
let
  nfsExports = [
    "var/lib/nfsroot/dacbert"
    "var/lib/nfsroot/riscbert"
    "var/lib/dump-dvb/whoopsie"
  ];

  reinstallDacbert = pkgs.writeScriptBin "reinstall-dacbert" ''
    SYSTEM=$(${lib.getExe pkgs.curl} -sLH "Accept: application/json" \
      https://hydra.hq.c3d2.de/job/c3d2/nix-config/dacbert/latest \
      | ${lib.getExe pkgs.jq} -er .buildoutputs.out.path
    )
    BOOT=$(${lib.getExe pkgs.curl} -sLH "Accept: application/json" \
      https://hydra.hq.c3d2.de/job/c3d2/nix-config/dacbert-tftproot/latest \
      | ${lib.getExe pkgs.jq} -er .buildoutputs.out.path
    )
    ${lib.getExe config.nix.package} --extra-experimental-features nix-command \
      copy \
      --from https://nix-cache.hq.c3d2.de \
      --to /var/lib/nfsroot/dacbert \
      --no-check-sigs \
      $SYSTEM $BOOT
    cp /var/lib/nfsroot/dacbert/$BOOT/* /var/lib/nfsroot/dacbert/boot/
  '';

in {
  imports = [
    ./tftp.nix
    ./nfs.nix
  ];

  microvm = {
    hypervisor = "cloud-hypervisor";
    mem = 2048;

    storeDiskType = "erofs";

    volumes = map (export: {
      mountPoint = "/${export}";
      image = "/dev/zvol/server10-root/vm/nfsroot/${builtins.baseNameOf export}";
      autoCreate = false;
    }) nfsExports;
  };

  c3d2.deployment = {
    server = "server10";
  };

  fileSystems = builtins.foldl' (fileSystems: export: fileSystems // {
    "/${export}".options = [ "relatime" "discard" ];
  }) {} nfsExports;

  networking = {
    hostName = "nfsroot";
    firewall.enable = false;
  };

  environment.systemPackages = [ reinstallDacbert ];

  system.stateVersion = "22.05";
}
