{
  lib,
  config,
  pkgs,
  ...
}:
let
  sql = pkgs.writeText "create-postgres-exporter.sql" ''
    -- To use IF statements, hence to be able to check if the user exists before
    -- attempting creation, we need to switch to procedural SQL (PL/pgSQL)
    -- instead of standard SQL.
    -- More: https://www.postgresql.org/docs/9.3/plpgsql-overview.html
    -- To preserve compatibility with <9.0, DO blocks are not used; instead,
    -- a function is created and dropped.
    CREATE OR REPLACE FUNCTION __tmp_create_user() returns void as $$
    BEGIN
      IF NOT EXISTS (
              SELECT                       -- SELECT list can stay empty for this
              FROM   pg_catalog.pg_user
              WHERE  usename = 'postgres_exporter') THEN
        CREATE USER postgres_exporter;
      END IF;
    END;
    $$ language plpgsql;

    SELECT __tmp_create_user();
    DROP FUNCTION __tmp_create_user();

    ALTER USER postgres_exporter SET SEARCH_PATH TO postgres_exporter,pg_catalog;

    -- If deploying as non-superuser (for example in AWS RDS), uncomment the GRANT
    -- line below and replace <MASTER_USER> with your root user.
    -- GRANT postgres_exporter TO <MASTER_USER>;

    GRANT CONNECT ON DATABASE postgres TO postgres_exporter;
    GRANT pg_monitor to postgres_exporter;
  '';
  script = pkgs.writeShellApplication {
    name = "postgresql-create-postgres-exporter";
    runtimeInputs = [ config.services.postgresql.package ];
    text = ''
      PSQL="psql --port=${builtins.toString config.services.postgresql.settings.port}"

      while ! $PSQL -d postgres -c "" 2> /dev/null; do
          sleep 0.1
      done

      $PSQL -tAf ${sql}
    '';
  };
in
{
  config =
    lib.mkIf
      (config.khscodes.infrastructure.vault-prometheus-sender.enable && config.services.postgresql.enable)
      {
        khscodes.infrastructure.vault-prometheus-sender.exporters.enabled = [ "postgres" ];
        services.prometheus.exporters.postgres = {
          enable = true;
          dataSourceName = "user=postgres_exporter host=/run/postgresql database=postgres sslmode=disable";
          user = "postgres_exporter";
          group = "postgres_exporter";
        };
        users.users.postgres_exporter = {
          enable = true;
          group = "postgres_exporter";
          isSystemUser = true;
        };
        users.groups.postgres_exporter = { };
        systemd.services.postgresql-create-postgres-exporter = {
          enable = true;
          after = [ "postgresql.service" ];
          requires = [ "postgresql.service" ];
          wantedBy = [ "multi-user.target" ];
          before = [ "prometheus-postgres-exporter.service" ];
          serviceConfig = {
            Type = "oneshot";
            ExecStart = [
              (lib.getExe script)
            ];
            User = "postgres";
            Group = "postgres";
          };
        };
      };
}
