{
  pkgs,
  config,
  lib,
  ...
}:
with lib;
let
  serviceName = "${config.networking.hostName}-grafana";
  gfDomain = "${
    config.clan.core.vars.generators."${serviceName}".files.subdomain.value
  }.${config.networking.fqdn}";

  settingsFormatIni = pkgs.formats.ini {
    listToValue = concatMapStringsSep " " (generators.mkValueStringDefault { });
    mkKeyValue = generators.mkKeyValueDefault {
      mkValueString = v: if v == null then "" else generators.mkValueStringDefault { } v;
    } "=";
  };
  configFile = settingsFormatIni.generate "config.ini" config.services.grafana.settings;
in
{
  clan.core.vars.generators."${serviceName}" = {
    files = {
      adminpassword.secret = true;
      subdomain.secret = false;
    };
    prompts = {
      subdomain = {
        persist = true;
        type = "line";
        description = "Sub-domain for Grafana. Default:(grafana)";
      };
      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 "grafana" > "$out"/subdomain
      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
    '';
  };

  systemd.services.grafana.serviceConfig.ExecStartPre = [
    "+${pkgs.writeShellScript "grafana-set-password" ''
      ${pkgs.grafana}/bin/grafana cli --homepath ${config.services.grafana.dataDir} --config ${configFile} admin reset-admin-password $(cat ${
        config.clan.core.vars.generators."${serviceName}".files.adminpassword.path
      })
    ''}"
  ];

  services.nginx.virtualHosts."${gfDomain}" = {
    forceSSL = true;
    useACMEHost = "${config.networking.fqdn}";
    locations."/" = {
      proxyPass = "http://localhost:${builtins.toString config.services.grafana.settings.server.http_port}";
    };
  };

}
