#include <microhttpd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/select.h>
#include <stdio.h>

#define PORT		8888
#define TIMEOUT		1 // second

static int	dummy(void			*cls,
		      struct MHD_Connection	*connection,
		      const char		*url,
		      const char		*method,
		      const char		*version,
		      const char		*upload_data,
		      size_t			*upload_data_size,
		      void			**ptr)
{ /*
    This handler never replies to requests, but this is for the sake
    of example.  Let's assume that we start some asynchronous
    computation, and will answer to the request later, from outside
    this callback.
  */
  return MHD_YES;
}

static void	clear_stack()
{
  char	stack[4096];

  memset(stack, 0, sizeof (stack));
}

int		main ()
{
  struct MHD_Daemon *const daemon =
    MHD_start_daemon(MHD_NO_FLAG, PORT, NULL, NULL, &dummy, NULL,
		     MHD_OPTION_CONNECTION_TIMEOUT, TIMEOUT, MHD_OPTION_END);
  if (NULL == daemon)
    return EXIT_FAILURE;
  for (;;) {
    fd_set			r, w, e;
    int				max_fd = -1;
    unsigned MHD_LONG_LONG	timeout;

    MHD_run(daemon);
    FD_ZERO(&r);
    FD_ZERO(&w);
    FD_ZERO(&e);
    if (MHD_get_fdset(daemon, &r, &w, &e, &max_fd) != MHD_YES)
      return EXIT_FAILURE;
    clear_stack(daemon, &timeout);
    if (MHD_get_timeout(daemon, &timeout) != MHD_YES)
      select(max_fd + 1, &r, &w, &e, NULL);
    else {
      struct timeval	tv = { .tv_sec = timeout / 1000,
			       .tv_usec = (timeout % 1000) * 1000 };
      if (!timeout) {
	fputc('.', stderr);
	fflush(stderr);
      }
      select(max_fd + 1, &r, &w, &e, &tv);
    }
  }
}
