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

  Challenger is free software; you can redistribute it and/or modify it under the
  terms of the GNU 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 challenger/challenger-admin.c
 * @brief Administer clients of a challenger service
 * @author Christian Grothoff
 */
#include "platform.h"
#include <gnunet/gnunet_util_lib.h>
#include <gnunet/gnunet_db_lib.h>
#include "challenger_util.h"
#include "challenger_database_lib.h"


/**
 * Prefix required for all Bearer tokens.
 */
#define RFC_8959_PREFIX "secret-token:"


/**
 * Return value from main().
 */
static int global_ret;

/**
 * -a option: client secret
 */
static char *client_secret;

/**
 * -m option: client ID
 */
static char *client_id;

/**
 * -d option: delete client
 */
static int del_flag;

/**
 * -q option: be quiet
 */
static int be_quiet;


/**
 * Main function that will be run.
 *
 * @param cls closure
 * @param args remaining command-line arguments
 * @param cfgfile name of the configuration file used (for saving, can be NULL!)
 * @param cfg configuration
 */
static void
run (void *cls,
     char *const *args,
     const char *cfgfile,
     const struct GNUNET_CONFIGURATION_Handle *cfg)
{
  const char *redirect_uri = args[0];
  struct CHALLENGER_DatabasePlugin *plugin;

  (void) cls;
  (void) cfgfile;
  if (NULL == redirect_uri)
  {
    fprintf (stderr,
             "challenger-admin must be invoked with the client REDIRECT URI as first argument\n");
    global_ret = EXIT_INVALIDARGUMENT;
    return;
  }
  if ( (NULL != client_secret) &&
       (0 != strncasecmp (client_secret,
                          RFC_8959_PREFIX,
                          strlen (RFC_8959_PREFIX))) )
  {
    fprintf (stderr,
             "CLIENT_SECRET must begin with `%s'\n",
             RFC_8959_PREFIX);
    global_ret = EXIT_INVALIDARGUMENT;
    return;
  }
  if (NULL ==
      (plugin = CHALLENGER_DB_plugin_load (cfg,
                                           false)))
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Failed to initialize database plugin.\n");
    global_ret = EXIT_NOTINSTALLED;
    return;
  }
  if (del_flag)
  {
    enum GNUNET_DB_QueryStatus qs;

    if (NULL != client_id)
    {
      fprintf (stderr,
               "'-m' and '-d' options cannot be used at the same time\n");
      global_ret = EXIT_INVALIDARGUMENT;
      goto cleanup;
    }
    qs = plugin->client_delete (plugin->cls,
                                redirect_uri);
    switch (qs)
    {
    case GNUNET_DB_STATUS_SOFT_ERROR:
    case GNUNET_DB_STATUS_HARD_ERROR:
      GNUNET_break (0);
      global_ret = EXIT_FAILURE;
      goto cleanup;
    case GNUNET_DB_STATUS_SUCCESS_NO_RESULTS:
      GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                  "Client with this CLIENT_REDIRECT_URI is not known.\n");
      global_ret = EXIT_FAILURE;
      goto cleanup;
    case GNUNET_DB_STATUS_SUCCESS_ONE_RESULT:
      GNUNET_log (GNUNET_ERROR_TYPE_MESSAGE,
                  "Client deleted\n");
      break;
    }
    goto cleanup;
  }
  if (NULL != client_id)
  {
    enum GNUNET_DB_QueryStatus qs;
    unsigned long long row_id;
    char dummy;

    if (1 !=
        sscanf (client_id,
                "%llu%c",
                &row_id,
                &dummy))
    {
      fprintf (stderr,
               "CLIENT_ID must be a positive number\n");
      global_ret = EXIT_INVALIDARGUMENT;
      goto cleanup;
    }

    qs = plugin->client_modify (plugin->cls,
                                row_id,
                                redirect_uri,
                                client_secret);
    switch (qs)
    {
    case GNUNET_DB_STATUS_SOFT_ERROR:
    case GNUNET_DB_STATUS_HARD_ERROR:
      GNUNET_break (0);
      global_ret = EXIT_FAILURE;
      goto cleanup;
    case GNUNET_DB_STATUS_SUCCESS_NO_RESULTS:
      GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                  "Client %llu not found.\n",
                  row_id);
      global_ret = EXIT_FAILURE;
      goto cleanup;
    case GNUNET_DB_STATUS_SUCCESS_ONE_RESULT:
      if (! be_quiet)
        fprintf (stdout,
                 "Client modified.\n");
      break;
    }
    goto cleanup;
  }
  if (NULL != client_secret)
  {
    enum GNUNET_DB_QueryStatus qs;
    uint64_t row_id;

    qs = plugin->client_check2 (plugin->cls,
                                redirect_uri,
                                client_secret,
                                &row_id);
    switch (qs)
    {
    case GNUNET_DB_STATUS_SOFT_ERROR:
    case GNUNET_DB_STATUS_HARD_ERROR:
      GNUNET_break (0);
      global_ret = EXIT_FAILURE;
      goto cleanup;
    case GNUNET_DB_STATUS_SUCCESS_NO_RESULTS:
      break;
    case GNUNET_DB_STATUS_SUCCESS_ONE_RESULT:
      if (be_quiet)
        fprintf (stdout,
                 "%llu\n",
                 (unsigned long long) row_id);
      else
        fprintf (stdout,
                 "Client added. Client ID is: %llu\n",
                 (unsigned long long) row_id);
      goto cleanup;
    }
    qs = plugin->client_add (plugin->cls,
                             redirect_uri,
                             client_secret,
                             &row_id);
    switch (qs)
    {
    case GNUNET_DB_STATUS_SOFT_ERROR:
    case GNUNET_DB_STATUS_HARD_ERROR:
      GNUNET_break (0);
      global_ret = EXIT_FAILURE;
      goto cleanup;
    case GNUNET_DB_STATUS_SUCCESS_NO_RESULTS:
      GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
                  "Client with this CLIENT_REDIRECT_URI already exists.\n");
      global_ret = EXIT_FAILURE;
      goto cleanup;
    case GNUNET_DB_STATUS_SUCCESS_ONE_RESULT:
      if (be_quiet)
        fprintf (stdout,
                 "%llu\n",
                 (unsigned long long) row_id);
      else
        fprintf (stdout,
                 "Client added. Client ID is: %llu\n",
                 (unsigned long long) row_id);
      break;
    }
    goto cleanup;
  }
cleanup:
  CHALLENGER_DB_plugin_unload (plugin);
}


/**
 * The main function of the client management tool.  Used to add or
 * remove clients from the Challenger' database.
 *
 * @param argc number of arguments from the command line
 * @param argv command line arguments
 * @return 0 ok, non-zero on error
 */
int
main (int argc,
      char *const *argv)
{
  struct GNUNET_GETOPT_CommandLineOption options[] = {
    GNUNET_GETOPT_option_string ('a',
                                 "add",
                                 "CLIENT_SECRET",
                                 "add client",
                                 &client_secret),
    GNUNET_GETOPT_option_flag ('d',
                               "delete",
                               "delete client",
                               &del_flag),
    GNUNET_GETOPT_option_string ('m',
                                 "modify-client",
                                 "CLIENT_ID",
                                 "modify existing client to use the given secret and redirect URL",
                                 &client_id),
    GNUNET_GETOPT_option_flag ('q',
                               "quiet",
                               "be less verbose in the output",
                               &be_quiet),
    /* FIXME: add -s / --show option */
    GNUNET_GETOPT_OPTION_END
  };
  enum GNUNET_GenericReturnValue ret;

  ret = GNUNET_PROGRAM_run (CHALLENGER_project_data (),
                            argc, argv,
                            "challenger-admin CLIENT_REDIRECT_URI",
                            "Tool to add, modify or remove clients from challenger",
                            options,
                            &run, NULL);
  if (GNUNET_SYSERR == ret)
    return EXIT_INVALIDARGUMENT;
  if (GNUNET_NO == ret)
    return EXIT_SUCCESS;
  return global_ret;
}


/* end of challenger-dbinit.c */
