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

let
  cfg = config.c3d2.hq.statistics;

  isMetal =
    !config.boot.isContainer &&
    !(config ? microvm);

in
{
  options.c3d2.hq.statistics = {
    enable = lib.mkEnableOption "statistics collection";
  };

  config = {
    services = lib.mkMerge [
      (let
        nginxStatusPort = 9100;
      in {
        collectd = lib.mkIf cfg.enable {
          enable = true;
          extraConfig = ''
            FQDNLookup false
            Interval 10
          '';
          buildMinimalPackage = true;
          plugins = {
            logfile = ''
              LogLevel info
              File STDOUT
            '';
            network = ''
              Server "grafana.serv.zentralwerk.org" "25826"
            '';
            memory = "";
            processes = "";
            disk = "";
            df = "";
            cpu = "";
            entropy = "";
            load = "";
            swap = "";
            cgroups = "";
            vmem = "";
            interface = "";
          } // lib.optionalAttrs isMetal {
            sensors = "";
            cpufreq = "";
            irq = "";
            ipmi = "";
            thermal = "";
          } // lib.optionalAttrs config.services.nginx.enable {
            nginx = ''
              URL "http://localhost:${toString nginxStatusPort}/nginx_status"
            '';
          };
        };

        nginx = lib.mkIf config.services.nginx.enable {
          virtualHosts.localhost = {
            listen = [
              { addr = "127.0.0.1"; port = nginxStatusPort; }
              { addr = "[::1]"; port = nginxStatusPort; }
            ];
            locations."/nginx_status".extraConfig = ''
              stub_status;

              access_log off;
              allow 127.0.0.1;
              allow ::1;
              deny all;
            '';
          };
        };
      })

      (lib.mkIf (pkgs.system != "riscv64-linux") {
        nginx = {
          enable = true;
          virtualHosts."_" = {
            listen =
              let
                port = 9100;
              in
              [
                { addr = "0.0.0.0"; inherit port; }
                { addr = "[::]"; inherit port; }
              ];
            locations."/metrics" = {
              proxyPass = "http://127.0.0.1:${toString config.services.prometheus.exporters.node.port}/metrics";
              extraConfig = libC.hqNetworkOnly;
            };
          };
        };

        prometheus.exporters.node = {
          enable = true;
          enabledCollectors = [ "ethtool" "systemd" ];
          listenAddress = "127.0.0.1";
          openFirewall = true;
          port = 9101;
        };
      })
    ];
  };
}
