{ config, containerCfg, pkgs, lib, builder, name, ... }:
let 
  serverCfg = config.syscfg.server;
  version = "latest";

  influxSource = pkgs.writers.writeYAML "influx.yaml" {
  apiVersion = 1;
  datasources = [
    {
      name = "Telegraf";
      type = "influxdb";
      access = "proxy";
      url = "http://influx-db:8181";
      jsonData = {
        version = "SQL";
        dbName = "telegraf";
        httpMode = "POST";
        insecureGrpc = true;
      };
      secureJsonData = {
        token = "\${INFLUXDB_TOKEN}"; 
      };
      isDefault = true;
      editable = true;
    }
  ];
};

in {
  requires = {
    secrets = [ name ];
    databases = [ name ];
  };

  runtime = {
    paths = [{
      path = "${serverCfg.path.config.path}/influxdb/";
      owner = "1500:1500";
      mode = "0755"; 
    }{
      path = "${serverCfg.path.data.path}/influxdb/";
      dirs = ["data" "ui"];
      owner = "1500:1500";
      mode = "0755"; 
    }];

    containers = {
      db = builder.mkContainer {
        image = "influxdb:3-core";
        secret = name;
        extraEnv = {
          INFLUXD_DB_PATH = "/db";
          INFLUXD_CONFIG_PATH = "/config";
        };
        overrides = {
          cmd = [ "influxdb3" "serve" "--node-id=node0" "--data-dir=/var/lib/influxdb3/data" "--admin-token-file=/var/lib/influxdb3/token.json" ];
          ports = [ "8181:8181" ];
          volumes = [
            "${serverCfg.path.data.path}/influxdb/data:/var/lib/influxdb3/data:rw"
            "${serverCfg.path.config.path}/influxdb/admin-token.json:/var/lib/influxdb3/token.json:ro"

          ];
        };
      };

      ui = if(containerCfg.extra?explorer) then builder.mkContainer {
        tmpfs = true;
        authentik = true;
        subdomain = containerCfg.subdomain;
        image = "influxdata/influxdb3-ui:${version}";
        port = 8080; # 8888 is something else
        secret = name;
        extraEnv = {
          DATABASE_URL = "/db/sqlite.db"; 
          DEFAULT_INFLUX_SERVER = "http://${builder.host}:8181";
        };
        overrides = {
          cmd = [ "--mode=admin" ]; 
          volumes = [
            "${serverCfg.path.data.path}/influxdb/ui:/db:rw"
            "${serverCfg.path.config.path}/influxdb/:/app-root/config:rw"
          ];
        };
      } else builder.mkContainer {
        tmpfs = true;
        authentik = true;
        subdomain = containerCfg.subdomain;
        image = "grafana/grafana:${version}";
        port = 3000;
        extraEnv = {
          GF_SERVER_ROOT_URL = "https://${containerCfg.subdomain}.${serverCfg.domain}";
          GF_DEFAULT_INSTANCE_NAME = serverCfg.domain;
          GF_SECURITY_ADMIN_USER = "\${DEFAULT_ADMIN_USERNAME}"; 
          GF_SECURITY_ADMIN_PASSWORD = "\${DEFAULT_ADMIN_PASSWORD}";
          GF_SECURITY_ADMIN_EMAIL = "\${DEFAULT_ADMIN_EMAIL}";
          GF_SECURITY_COOKIE_SECURE = "true";
          GF_USERS_ALLOW_SIGN_UP = "false";
          GF_USERS_AUTO_ASSIGN_ORG = "true";
          GF_USERS_AUTO_ASSIGN_ORG_ROLE = "true";
          GF_AUTH_PROXY_ENABLED = "true";
          GF_AUTH_PROXY_HEADER_NAME = "X-authentik-username";
          GF_AUTH_PROXY_HEADER_PROPERTY = "username";
          GF_AUTH_PROXY_AUTO_SIGN_UP = "true";
          GF_DATABASE_TYPE = "postgres";
          GF_DATABASE_HOST = "${builder.host}";
          GF_DATABASE_NAME = "influx_db";
          GF_DATABASE_USER = "influx_user";
          GF_ANALYTICS_REPORTING_ENABLED = "false";
          GF_CHECK_FOR_UPDATED = "false";
          GF_LIVE_HA_ENGINE = "redis";
          GF_LIVE_HA_ENGINE_ADRESS = "${builder.host}:6379";
          DEFAULT_INFLUX_SERVER = "http://${builder.host}:8181";
        };
        overrides = { 
          user = "1500:1500";
          environmentFiles =  [ config.sops.secrets."INFLUX".path config.sops.secrets."CUSTOM".path ] ;
          volumes = [
            "${serverCfg.path.data.path}/influxdb/ui:/var/lib/grafana:rw"
            "${influxSource}:/etc/grafana/provisioning/datasources/influx.yaml:ro"
          ];
        };
      };
    };

    setup = {
      trigger = "db";
      envFile =  config.sops.secrets."INFLUX".path;
      script = pkgs.writeShellScript "setup" ''
        cat > ${serverCfg.path.config.path}/influxdb/config.json << EOF
{
  "DEFAULT_INFLUX_SERVER": "http://${builder.host}:8181",
  "DEFAULT_INFLUX_DATABASE": "main",
  "DEFAULT_API_TOKEN": "$INFLUXDB_TOKEN",
  "DEFAULT_SERVER_NAME": "${serverCfg.domain}"
}
EOF

      cat > ${serverCfg.path.config.path}/influxdb/admin-token.json << EOF
{
  "token": "$INFLUXDB_TOKEN",
  "name": "admin",
  "description": "Admin token for automated deployment"
}
EOF
      '';
    };
  };
}
