{
  config,
  lib,
  ...
}:
let
  pgsqlEnable = config.machine.postgresql.enable;
  cfg = config.machine.nextcloud;
in
with lib;
mkIf cfg.enable {
  services.nextcloud.config =
    if pgsqlEnable then
      {
        dbtype = "pgsql";
        dbhost = "localhost:${toString config.machine.postgresql.port}";
      }
    else
      {
        dbtype = "sqlite";
        dbhost = "localhost";
      };

  services.postgresql =
    with lib;
    mkIf pgsqlEnable {
      ensureDatabases = [ "nextcloud" ];
      ensureUsers = [
        {
          name = "nextcloud";
          ensureDBOwnership = true;
        }
      ];
    };
}
