{ config, ... }:

let
  secret = name: config.age.secrets."influxdb2-${name}".path;
  token = user: secret "${user}_token_file";

  host = "influx.dgnum.eu";
in

{
  services.influxdb2 = {
    enable = true;

    provision = {
      enable = true;

      organizations = {
        dgnum = {
          description = "DGNum org";
          buckets.telegraf.description = "Telegraf bucket";
          auths = {
            telegraf = {
              writeBuckets = [ "telegraf" ];
              tokenFile = token "telegraf";
            };

            grafana = {
              readPermissions = [ "buckets" ];
              tokenFile = token "grafana";
            };
          };
        };
      };

      initialSetup = {
        tokenFile = token "initial";
        passwordFile = secret "initial_password_file";
        organization = "main";
        bucket = "main";
      };
    };
  };

  services.nginx.virtualHosts.${host} = {
    enableACME = true;
    forceSSL = true;

    locations."/" = {
      proxyPass = "http://127.0.0.1:8086";
    };
  };

  age-secrets.autoMatch = [ "influxdb2" ];
}