{ pkgs
, lib
, config
, ... }: with lib; let
  cfg = config.global.netdata;
in {
  options.global.netdata = {
    enable = mkEnableOption "netdata";
    host = mkOption {
      type = with types; str;
      default = "localhost";
      description = "hostname of netdata web interface";
    };
    addSSL = mkEnableOption "add SSL to netdata proxy";
    useACMEHost = mkOption {
      type = with types; nullOr str;
      default = null;
      description = "existing acme host";
    };
    basicAuthFile = mkOption {
      type = with types; nullOr path;
      default = "/nix/persist/secret/netdata";
      description = "path to passwd file";
    };
  };

  config = mkIf cfg.enable {
    services.netdata = {
      enable = true;
      config = {
        global = {
          "error log" = "syslog";
          "access log" = "none";
          "debug log" = "syslog";
        };
        web."bind to" = "unix:/var/run/netdata/netdata.sock";
      };
    };

    users.users.netdata.uid = 287;
    users.groups.netdata.gid = 287;

    services.nginx.enable = mkDefault true;
    services.nginx.virtualHosts.${cfg.host} = {
      inherit (cfg) addSSL useACMEHost basicAuthFile;
      locations."/".proxyPass = "http://unix:/var/run/netdata/netdata.sock";
    };
    users.users.nginx.extraGroups = [ "netdata" ];

    environment.persistence."/nix/persist/fhs".directories = [ "/var/lib/netdata" ];
  };
}