{
  config,
  lib,
  namespace,
  ...
}:
with lib;
let
  name = "grafana";
  cfg = config.${namespace}.services.${name};

  grafanaConfig = lib.${namespace}.mkModule {
    inherit config name;
    description = "grafana";
    options = { };
    moduleConfig = {
      services = {
        prometheus = {
          enable = true;
          exporters = {
            node = {
              enable = true;
              enabledCollectors = [
                "filesystem"
                "diskstats"
                "meminfo"
                "cpu"
                "systemd" # Ensures systemd collector is enabled
                "processes"
              ];
              extraFlags = [
                "--collector.filesystem.mount-points-exclude=^/(dev|proc|sys|run)($|/)"
              ];
            };
            libvirt = {
              enable = false;
              openFirewall = true;
            };
            nut = {
              enable = true;
              openFirewall = true;
              passwordPath = config.sops.secrets."jallen-nas/ups_password".path;
              nutUser = upsUser;
            };
            # restic = {
            #   enable = true;
            #   openFirewall = true;
            #   resticPort = 8008;
            # };
          };
          scrapeConfigs = [
            {
              job_name = "node";
              static_configs = [
                {
                  targets = [ "localhost:${toString config.services.prometheus.exporters.node.port}" ];
                }
              ];
            }
            {
              job_name = "traefik";
              static_configs = [
                {
                  targets = [ "localhost:8082" ];
                }
              ];
            }
          ];
        };

        grafana = {
          enable = true;
          settings = {
            server = {
              http_port = cfg.port;
              http_addr = "0.0.0.0";
            };
          };

          dataDir = "/media/nas/main/nix-app-data/grafana";

          provision = {
            enable = true;
            datasources.settings.datasources = [
              {
                name = "Prometheus";
                type = "prometheus";
                access = "proxy";
                url = "http://localhost:${toString config.services.prometheus.port}";
              }
            ];
          };
        };
      };
    };
  };

  upsUser = "nas-admin";
in
{
  imports = [ grafanaConfig ];
}
