/*
  This file is part of TALER
  Copyright (C) 2020, 2023, 2024 Taler Systems SA

  TALER 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.

  TALER is distributed in the hope that it will be useful, but WITHOUT ANY
  WARRANTY; without even the implied warranty of EXCHANGEABILITY 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
  TALER; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
*/
/**
 * @file mhd_spa.c
 * @brief logic to load single page apps
 * @author Christian Grothoff
 */
#include "taler/platform.h"
#include <gnunet/gnunet_util_lib.h>
#include "taler/taler_util.h"
#include "taler/taler_mhd_lib.h"
#include <gnunet/gnunet_mhd_compat.h>


/**
 * Resource from the WebUi.
 */
struct WebuiFile
{
  /**
   * Kept in a DLL.
   */
  struct WebuiFile *next;

  /**
   * Kept in a DLL.
   */
  struct WebuiFile *prev;

  /**
   * Path this resource matches.
   */
  char *path;

  /**
   * SPA resource, deflate compressed.
   */
  struct MHD_Response *responses[TALER_MHD_CT_MAX];

};


/**
 * Resource from the WebUi.
 */
struct TALER_MHD_Spa
{
  /**
   * Resources of the WebUI, kept in a DLL.
   */
  struct WebuiFile *webui_head;

  /**
   * Resources of the WebUI, kept in a DLL.
   */
  struct WebuiFile *webui_tail;
};


MHD_RESULT
TALER_MHD_spa_handler (const struct TALER_MHD_Spa *spa,
                       struct MHD_Connection *connection,
                       const char *path)
{
  struct WebuiFile *w = NULL;
  enum TALER_MHD_CompressionType comp;

  if ( (NULL == path) ||
       (0 == strcmp (path,
                     "")) )
    path = "index.html";
  for (struct WebuiFile *pos = spa->webui_head;
       NULL != pos;
       pos = pos->next)
    if (0 == strcmp (path,
                     pos->path))
    {
      w = pos;
      break;
    }
  if ( (NULL == w) ||
       (NULL == w->responses[TALER_MHD_CT_NONE]) )
    return TALER_MHD_reply_with_error (connection,
                                       MHD_HTTP_NOT_FOUND,
                                       TALER_EC_GENERIC_ENDPOINT_UNKNOWN,
                                       path);
  comp = TALER_MHD_can_compress (connection,
                                 TALER_MHD_CT_MAX - 1);
  GNUNET_assert (comp < TALER_MHD_CT_MAX);
  GNUNET_assert (comp >= 0);
  if (NULL != w->responses[comp])
    return MHD_queue_response (connection,
                               MHD_HTTP_OK,
                               w->responses[comp]);
  return MHD_queue_response (connection,
                             MHD_HTTP_OK,
                             w->responses[TALER_MHD_CT_NONE]);
}


/**
 * Function called on each file to load for the WebUI.
 *
 * @param cls the `struct TALER_MHD_Spa *` to build
 * @param dn name of the file to load
 */
static enum GNUNET_GenericReturnValue
build_webui (void *cls,
             const char *dn)
{
  static const struct
  {
    const char *ext;
    const char *mime;
  } mime_map[] = {
    {
      .ext = "css",
      .mime = "text/css"
    },
    {
      .ext = "html",
      .mime = "text/html"
    },
    {
      .ext = "js",
      .mime = "text/javascript"
    },
    {
      .ext = "jpg",
      .mime = "image/jpeg"
    },
    {
      .ext = "jpeg",
      .mime = "image/jpeg"
    },
    {
      .ext = "png",
      .mime = "image/png"
    },
    {
      .ext = "svg",
      .mime = "image/svg+xml"
    },
    {
      .ext = NULL,
      .mime = NULL
    },
  };
  struct TALER_MHD_Spa *spa = cls;
  int fd;
  struct stat sb;
  struct MHD_Response *response;
  char *ext;
  const char *mime;
  const char *slash;
  char *fn;
  const char *cts = NULL;
  enum TALER_MHD_CompressionType ct = TALER_MHD_CT_NONE;

  slash = strrchr (dn, '/');
  if (NULL == slash)
  {
    GNUNET_break (0);
    return GNUNET_SYSERR;
  }
  fd = open (dn,
             O_RDONLY);
  if (-1 == fd)
  {
    GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
                              "open",
                              dn);
    return GNUNET_SYSERR;
  }
  if (0 !=
      fstat (fd,
             &sb))
  {
    GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR,
                              "open",
                              dn);
    GNUNET_break (0 == close (fd));
    return GNUNET_SYSERR;
  }

  fn = GNUNET_strdup (slash + 1);
  ext = strrchr (fn,
                 '.');
  if (NULL == ext)
  {
    GNUNET_break (0 == close (fd));
    GNUNET_free (fn);
    return GNUNET_OK;
  }
  if (0 == strcmp (ext,
                   ".gz"))
  {
    cts = "gzip";
    ct = TALER_MHD_CT_GZIP;
    *ext = '\0';
    ext = strrchr (fn, '.');
  }
  if (0 == strcmp (ext,
                   ".zstd"))
  {
    cts = "zstd";
    ct = TALER_MHD_CT_ZSTD;
    *ext = '\0';
    ext = strrchr (fn, '.');
  }
  if (NULL == ext)
  {
    GNUNET_break (0 == close (fd));
    GNUNET_free (fn);
    return GNUNET_OK;
  }
  ext++;

  mime = NULL;
  for (unsigned int i = 0; NULL != mime_map[i].ext; i++)
    if (0 == strcasecmp (ext,
                         mime_map[i].ext))
    {
      mime = mime_map[i].mime;
      break;
    }

  response = MHD_create_response_from_fd (
    sb.st_size,
    fd /* FD now owned by MHD! */);
  if (NULL == response)
  {
    GNUNET_free (fn);
    return GNUNET_SYSERR;
  }
  if ( (NULL != cts) &&
       (MHD_NO ==
        MHD_add_response_header (response,
                                 MHD_HTTP_HEADER_CONTENT_ENCODING,
                                 cts)) )
  {
    GNUNET_break (0);
    MHD_destroy_response (response);
    GNUNET_free (fn);
    return GNUNET_SYSERR;
  }
  if (NULL != mime)
  {
    GNUNET_break (MHD_YES ==
                  MHD_add_response_header (response,
                                           MHD_HTTP_HEADER_CONTENT_TYPE,
                                           mime));
  }

  {
    struct WebuiFile *w;

    for (w = spa->webui_head;
         NULL != w;
         w = w->next)
    {
      if (0 == strcmp (fn,
                       w->path))
        break;
    }
    if (NULL == w)
    {
      w = GNUNET_new (struct WebuiFile);
      w->path = fn;
      GNUNET_CONTAINER_DLL_insert (spa->webui_head,
                                   spa->webui_tail,
                                   w);
    }
    else
    {
      GNUNET_free (fn);
    }
    GNUNET_assert (NULL == w->responses[ct]);
    w->responses[ct] = response;
  }
  return GNUNET_OK;
}


struct TALER_MHD_Spa *
TALER_MHD_spa_load_dir (const char *dn)
{
  struct TALER_MHD_Spa *spa;

  spa = GNUNET_new (struct TALER_MHD_Spa);
  if (-1 ==
      GNUNET_DISK_directory_scan (dn,
                                  &build_webui,
                                  spa))
  {
    GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
                "Failed to load WebUI from `%s'\n",
                dn);
    TALER_MHD_spa_free (spa);
    return NULL;
  }
  return spa;
}


struct TALER_MHD_Spa *
TALER_MHD_spa_load (const struct GNUNET_OS_ProjectData *pd,
                    const char *dir)
{
  char *dn;
  char *path;

  path = GNUNET_OS_installation_get_path (pd,
                                          GNUNET_OS_IPK_DATADIR);
  if (NULL == path)
  {
    GNUNET_break (0);
    return NULL;
  }
  GNUNET_asprintf (&dn,
                   "%s%s",
                   path,
                   dir);
  GNUNET_free (path);
  return TALER_MHD_spa_load_dir (dn);
}


void
TALER_MHD_spa_free (struct TALER_MHD_Spa *spa)
{
  struct WebuiFile *w;

  while (NULL != (w = spa->webui_head))
  {
    GNUNET_CONTAINER_DLL_remove (spa->webui_head,
                                 spa->webui_tail,
                                 w);
    for (enum TALER_MHD_CompressionType ct = TALER_MHD_CT_NONE;
         ct < TALER_MHD_CT_MAX;
         ct++)
    {
      if (NULL != w->responses[ct])
      {
        MHD_destroy_response (w->responses[ct]);
        w->responses[ct] = NULL;
      }
    }
    GNUNET_free (w->path);
    GNUNET_free (w);
  }
  GNUNET_free (spa);
}
