/* main.c */

#include <pthread.h>
#include <stdio.h>			/* For NULL */
#include <fcntl.h>			/* For O_RDONLY */
#include "accept_buf.h"

void * new_connection (void * buf)
{
    struct accept_buf * my_connection = (struct accept_buf *)buf;
	int count, in_fd, i;
	char in_buf[1024];

    /* Do some real work here */
	if ((count = read(my_connection->fd, in_buf, 1023)) > 0) {
		in_buf[1024] = '\0';
		write(1, in_buf, count);
		for (i = 0; i < count; i++) {
			if (isspace(in_buf[i])) {
				in_buf[i] = '\0';
				break;
			}
		}
		if ((in_fd = open(in_buf, O_RDONLY)) >= 0) {
			while ((count = read(in_fd, in_buf, 1024)) > 0) {
				write(my_connection->fd, in_buf, count);
			}
		}
	}

    /* Close connection and free buffer */
	close(my_connection->fd);
	accept_buf_free(my_connection);
    pthread_exit(NULL);
}

int accept_count_max = 10;
int accept_count = 0;
short port = 8002;

int main(int argc, char ** argv)
{
    struct sockaddr_in connect_addr;
    struct accept_buf * buf;
    int connect_port, len;
    pthread_t thread_id;

	pthread_init();
	accept_buf_init(10);

    /* Setup server */
	if ((connect_port = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		/* Error */
		exit(1);
	}

	connect_addr.sin_family 		= AF_INET;
	connect_addr.sin_port 			= htons(port);
	connect_addr.sin_addr.s_addr	= INADDR_ANY;

	if (bind(connect_port, (struct sockaddr *)(&connect_addr),
       sizeof(connect_addr))) {
		/* Error */
		exit(1);
	}

    listen(connect_port, 8);

    while (1) {
        /* Allocte a new accept buffer */
		buf = accept_buf_malloc();

		no_malloc:;
        if ((buf->fd = accept(connect_port, &(buf->addr), &len)) < 0) {
		    /* Error condition */
		    break;
        }

        if (pthread_create(&thread_id, NULL, new_connection, (void *)buf)) {
            /* Send an error back to the connector */

            /* Close connection and free buffer */
			close(buf->fd);
			goto no_malloc;
        }
		pthread_detach(thread_id);
    }

	/* At least let all the current connections finish */
	pthread_exit(NULL);
}

