/***************************************************************************
 *                                  _   _ ____  _
 *  Project                     ___| | | |  _ \| |
 *                             / __| | | | |_) | |
 *                            | (__| |_| |  _ <| |___
 *                             \___|\___/|_| \_\_____|
 *
 * Copyright (C) 1998 - 2012, Daniel Stenberg, <daniel@haxx.se>, et al.
 *
 * This software is licensed as described in the file COPYING, which
 * you should have received as part of this distribution. The terms
 * are also available at http://curl.haxx.se/docs/copyright.html.
 *
 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
 * copies of the Software, and permit persons to whom the Software is
 * furnished to do so, under the terms of the COPYING file.
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
 * KIND, either express or implied.
 *
 ***************************************************************************/

#include "setup.h"
#include "curl_threads.h"

#if defined(USE_LWIPSOCK)
#include <conio.h>
#include <lwip/netif.h>
#include <lwip/dhcp.h>
#include <lwip/sys.h>
#include <lwip/tcpip.h>
#include <pcapif.h>      /* in <lwIP-root>/src/contrib/ports/win32/ */

static struct netif  netif;
static unsigned char debug_flags;
static ip_addr_t     ipaddr, netmask, gw; /* (manually) host IP configuration */
static sys_sem_t     init_sem;
static BOOL          quit = FALSE;

static DWORD CURL_STDCALL main_thread(void *arg);

void curl_lwip_init (void)
{
  struct packet_adapter *pa;

  IP4_ADDR(&gw, 10,0,0,1);
  IP4_ADDR(&netmask, 255,255,255,0);
  IP4_ADDR(&ipaddr, 10,0,0,3);

  lwip_init();
  sys_sem_new(&init_sem, 0);
  netif_init();

#if 0
  if (!netif.state)
     abort();
#endif

  sys_thread_new("main_thread", (lwip_thread_fn)main_thread, &init_sem,
                 DEFAULT_THREAD_STACKSIZE, DEFAULT_THREAD_PRIO);
}

static void tcpip_init_done (void *arg)
{
  sys_sem_t *sem = (sys_sem_t*)arg;
  struct netif *iface = netif_add(&netif, &ipaddr, &netmask, &gw, NULL, pcapif_init, tcpip_input);

  netif_set_default(iface);
  netif_set_up(&netif);

  sys_sem_signal(sem);
}

static DWORD CURL_STDCALL main_thread (void *arg)
{
  struct in_addr inaddr;
  char ip_str[16] = {0}, nm_str[16] = {0}, gw_str[16] = {0};
  sys_sem_t *sem = (sys_sem_t*) arg;

  tcpip_init(tcpip_init_done, sem);
  sys_sem_wait(sem);

  inaddr.s_addr = ipaddr.addr;
  strncpy(ip_str,inet_ntoa(inaddr),sizeof(ip_str));
  inaddr.s_addr = netmask.addr;
  strncpy(nm_str,inet_ntoa(inaddr),sizeof(nm_str));
  inaddr.s_addr = gw.addr;
  strncpy(gw_str,inet_ntoa(inaddr),sizeof(gw_str));

  printf("TCP/IP initialized. Using IP %s, netmask %s, gateway %s\n",
         ip_str, nm_str, gw_str);

  while (!_kbhit())
  {
    netif_poll(&netif);
    Sleep (10);
  }
  sys_sem_free(sem);
}
#endif


