/*
  This file is part of Challenger
  Copyright (C) 2019 Taler Systems SA

  Challenger is free software; you can redistribute it and/or modify it under the
  terms of the GNU Lesser General Public License as published by the Free Software
  Foundation; either version 3, or (at your option) any later version.

  Challenger is distributed in the hope that it will be useful, but WITHOUT ANY
  WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  A PARTICULAR PURPOSE.  See the GNU General Public License for more details.

  You should have received a copy of the GNU General Public License along with
  Challenger; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
*/
/**
 * @file challengerdb/challenger_db_plugin.c
 * @brief Logic to load database plugin
 * @author Christian Grothoff
 * @author Sree Harsha Totakura <sreeharsha@totakura.in>
 */
#include "platform.h"
#include "challenger_util.h"
#include "challenger_database_lib.h"
#include <ltdl.h>


struct CHALLENGER_DatabasePlugin *
CHALLENGER_DB_plugin_load (const struct GNUNET_CONFIGURATION_Handle *cfg,
                           bool skip_preflight)
{
  char *plugin_name;
  char *lib_name;
  struct CHALLENGER_DatabasePlugin *plugin;

  if (GNUNET_SYSERR ==
      GNUNET_CONFIGURATION_get_value_string (cfg,
                                             "challenger",
                                             "db",
                                             &plugin_name))
  {
    GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
                               "challenger",
                               "db");
    return NULL;
  }
  (void) GNUNET_asprintf (&lib_name,
                          "libchallenger_plugin_db_%s",
                          plugin_name);
  GNUNET_free (plugin_name);
  plugin = GNUNET_PLUGIN_load (CHALLENGER_project_data (),
                               lib_name,
                               (void *) cfg);
  if (NULL == plugin)
  {
    GNUNET_free (lib_name);
    return NULL;
  }
  plugin->library_name = lib_name;
  if ( (! skip_preflight) &&
       (GNUNET_OK !=
        plugin->preflight (plugin->cls)) )
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Database not ready. Try running challenger-dbinit!\n");
    CHALLENGER_DB_plugin_unload (plugin);
    return NULL;
  }
  return plugin;
}


void
CHALLENGER_DB_plugin_unload (struct CHALLENGER_DatabasePlugin *plugin)
{
  char *lib_name;

  if (NULL == plugin)
    return;
  lib_name = plugin->library_name;
  GNUNET_assert (NULL == GNUNET_PLUGIN_unload (lib_name,
                                               plugin));
  GNUNET_free (lib_name);
}


/* end of challenger_db_plugin.c */
