{ config, pkgs, ... }:
let
  vmDomain = "${config.clan.core.vars.generators.b4l-victoriametrics.files.subdomain.value}.${config.networking.fqdn}";
in
{
  clan.core.vars.generators.b4l-victoriametrics = {
    files.subdomain.secret = false;
    files.adminuser.secret = false;
    files.adminpassword.secret = true;

    prompts = {
      subdomain = {
        persist = true;
        type = "line";
        description = "Sub-domain for Victoria Metrics app. Default:(metrics)";
      };
      adminuser = {
        persist = true;
        type = "line";
        description = "Username for an admin user. Default:(admin)";
      };
      adminpassword = {
        persist = true;
        type = "hidden";
        description = "Password for the admin user. Leave empty to auto-generate.";
      };
    };

    runtimeInputs = [
      pkgs.xkcdpass
      pkgs.coreutils
    ];

    script = ''
      prompt_domain=$(cat "$prompts"/subdomain)
      if [[ -n "''${prompt_domain-}" ]]; then
        echo $prompt_domain | tr -d "\n" > "$out"/subdomain
      else
        echo -n "metrics" > "$out"/subdomain
      fi

      prompt_adminuser=$(cat "$prompts"/adminuser)
      if [[ -n "''${prompt_adminuser-}" ]]; then
        echo $prompt_adminuser | tr -d "\n" > "$out"/adminuser
      else
        echo -n "admin" > "$out"/adminuser
      fi

      prompt_password=$(cat "$prompts"/adminpassword)
      if [[ -n "''${prompt_password-}" ]]; then
        echo "$prompt_password" | tr -d "\n" > "$out"/adminpassword
      else
        xkcdpass --numwords 4 --delimiter - --count 1 | tr -d "\n" > "$out"/adminpassword
      fi
    '';
  };

  services.victoriametrics = {
    extraOptions = [
      "-httpAuth.username=file://${config.clan.core.vars.generators.b4l-victoriametrics.files.adminuser.path}"
      "-httpAuth.password=file://${config.clan.core.vars.generators.b4l-victoriametrics.files.adminpassword.path}"
    ];
  };

  services.nginx.virtualHosts."${vmDomain}" = {
    forceSSL = true;
    useACMEHost = "${config.networking.fqdn}";
    locations."/" = {
      proxyPass = "http://localhost${builtins.toString config.services.victoriametrics.listenAddress}";
    };
  };

}
