{
  config,
  lib,
  ...
}:
let
  pgsqlEnable = config.machine.postgresql.enable;
  inherit (config.machine.synapse) enable;
in
with lib;
mkIf enable {
  services.postgresql =
    with lib;
    mkIf pgsqlEnable {
      ensureUsers = [
        {
          name = "matrix-synapse";
          ensureDBOwnership = true;
        }
      ];
      ensureDatabases = [ "matrix-synapse" ];
    };
  services.matrix-synapse.settings.database = {
    name = if pgsqlEnable then "psycopg2" else "sqlite3";
    args =
      with lib;
      mkIf pgsqlEnable {
        host = "/run/postgresql";
      };
  };
}
