{ config, lib, pkgs, ... }:

{
  imports = [ ./neighbours.nix ];

  microvm.interfaces = [{
    type = "tap";
    id = "c3d2-nncp";
    mac = "de:ec:9a:6f:3f:63";
  }];

  c3d2 = {
    deployment = {
      server = "server10";
      autoNetSetup = false;
    };
    hq.statistics.enable = true;
    nncp.mergeSettings = false;
  };

  system.stateVersion = "22.05";

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

  programs.nncp = {
    enable = true;
    secrets = [ "/etc/nncp.secrets" ];
    settings = {
      mcd-listen = [ "c3d2" ];
      mcd-send.c3d2 = 60;
      neigh = # use c3d2.nncp.neigh but remove this node
        let
          hourlyCall = {
            cron = "0 42 * * * * *";
            xx = "tx"; # transmit only
            when-tx-exists = true;
          };
        in lib.mapAttrs (_: value:
          value // {
            via = lib.lists.remove "c3d2" value.via;
          } // (lib.attrsets.optionalAttrs (value.addrs or { } != { }) {
            calls = [ hourlyCall ];
          })) (builtins.removeAttrs config.c3d2.nncp.neigh [ "c3d2" ]);
    };
  };

  services.collectd.plugins.exec = let
    util =
      pkgs.runCommand "collectd_nncp" { nativeBuildInputs = [ pkgs.nim ]; } ''
        cp ${./collectd_nncp.nim} ./collectd_nncp.nim
        nim c --nimcache:. -o:$out ./collectd_nncp.nim
      '';
  in ''
    Exec "${config.services.collectd.user}" "${util}" "${config.programs.nncp.settings.spool}"
  '';
  users.groups.uucp.members = [ config.services.collectd.user ];

  services.nncp = {
    caller = {
      enable = true;
      extraArgs = [ "-autotoss" ];
    };
    daemon = {
      enable = true;
      socketActivation.enable = false;
      extraArgs = [ "-autotoss" ];
    };
  };
}
