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

let
  cfg = config.c3d2.hq.statistics;

  isMetal = !config.boot.isContainer && !(config ? microvm);
  supportsNodeExporter = config.nixpkgs.system != "riscv64-linux";

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

  config = {
    networking.firewall.allowedTCPPorts = [ 9100 ];

    services = {
      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 = {
        # nginx only needs to be explicitly enabled when proxing node_exporter
        enable = lib.mkIf supportsNodeExporter true;

        virtualHosts = {
          # only required when proxying node_exporter
          "_" = lib.mkIf supportsNodeExporter {
            listen = [
              { addr = "0.0.0.0"; port = nginxStatusPort; }
              { addr = "[::]"; port = nginxStatusPort; }
            ];
            locations."/metrics" = {
              proxyPass = "http://127.0.0.1:${toString config.services.prometheus.exporters.node.port}/metrics";
              extraConfig = libC.hqNetworkOnly;
            };
          };

          localhost = lib.mkIf cfg.enable {
            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;
            '';
          };
        };
      };

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