#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <fcntl.h>
#include "rws.h"

int
rws_connect()
{
  struct sockaddr_in sin;

  int sock = socket(AF_INET, SOCK_STREAM, 0);

  memset(&sin, 0, sizeof(sin));
  sin.sin_port = htons(8090);
  bind(sock, (struct sockaddr *) &sin, sizeof (sin));
  listen(sock, 5);

  return sock;
}

void
rws_accept(int sock)
{
  struct sockaddr_in sin;
  int len = sizeof(sin);
  char readbuf[4096];
  stream_t s;
  pool_t *pool;
  request_t *req;
  char *buf = ("HTTP/1.0 200 OK\r\n"
	       "\r\n");

  int buflen = strlen(buf);

  int fd;
  int ch;
  int subfd;
  int readlen = 0;

  memset(&req, 0, sizeof(request_t));

  while (1) {
    fd = accept(sock, (struct sockaddr *) &sin, &len);

    rws_open(&s, fd);
    
    pool = rws_create_pool();
    req = rws_malloc(pool, sizeof(request_t));
    memset(req, 0, sizeof(request_t));
    req->pool = pool;
    rws_scan_request(&s, req);
    
    rws_write(&s, buf, buflen);

    if (readlen <= 0) {
      subfd = open("/home/ferg/ws/resin/doc/test/hello_file.html", O_RDONLY);

      readlen = read(subfd, readbuf, sizeof(readbuf));
      
      close(subfd);
    }

    if (readlen >= 0) {
      rws_write(&s, readbuf, readlen);
      rws_flush(&s);
    }

    rws_close(&s);

    rws_free_pool(pool);
  }
}

int
main()
{
  int sock = rws_connect();
  rws_accept(sock);
}
