{ pkgs, config, ... }:
let
  domain = "metrics.${config.services.nginx.domain}";
in
{
  networking.firewall.allowedTCPPorts = [
    80
    443
  ];

  services.grafana = {
    enable = true;
    settings = {
      server = {
        http_port = 3001; # Default overlaps with gitea
        root_url = "https://metrics.tlater.net";
      };

      security = {
        admin_user = "tlater";
        admin_password = "$__file{${config.sops.secrets."grafana/adminPassword".path}}";
        secret_key = "$__file{${config.sops.secrets."grafana/secretKey".path}}";
        cookie_secure = true;
        cookie_samesite = "strict";
        content_security_policy = true;
      };

      database = {
        user = "grafana";
        name = "grafana";
        type = "postgres";
        host = "/run/postgresql";
      };
    };

    declarativePlugins = [
      pkgs.grafanaPlugins.victoriametrics-metrics-datasource
      pkgs.grafanaPlugins.victoriametrics-logs-datasource
    ];

    provision = {
      enable = true;

      datasources.settings.datasources = [
        {
          name = "Victoriametrics - tlater.net";
          url = "http://localhost:8428";
          type = "victoriametrics-metrics-datasource";
          access = "proxy";
          isDefault = true;
        }

        {
          name = "Victorialogs - tlater.net";
          url = "http://${config.services.victorialogs.bindAddress}";
          type = "victoriametrics-logs-datasource";
          access = "proxy";
        }
      ];
    };
  };

  services.nginx.virtualHosts."${domain}" = {
    forceSSL = true;
    useACMEHost = "tlater.net";
    enableHSTS = true;
    locations = {
      "/".proxyPass = "http://localhost:${toString config.services.grafana.settings.server.http_port}";
      "/api/live" = {
        proxyWebsockets = true;
        proxyPass = "http://localhost:${toString config.services.grafana.settings.server.http_port}";
      };
    };
  };

  sops.secrets = {
    "grafana/adminPassword" = {
      owner = "grafana";
      group = "grafana";
    };
    "grafana/secretKey" = {
      owner = "grafana";
      group = "grafana";
    };
  };
}
