#include "server.h"
#include "Session.h"

int
main(int argc, char* argv[])
{
	int port = 8000;
	int c;
	while ((c=getopt(argc, argv, "p:d"))!=-1) {
		switch (c) {
		case 'p':
			port = atoi(optarg);
			break;

		case 'd':
			HTLIB_SetLogLevel(HTLIB_LV_DEBUG);
			break;
			
		default:
			fprintf(stderr, "Usage: %s [-p port] [-d] \n", argv[0]);
			return 1;
		}
	}
	int s = socket(PF_INET, SOCK_STREAM, 0);
	if (s == -1) {
		perror("socket");
		return 2;
	}

	int on = 1;
	if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on))==-1) {
		perror("setsockopt");
		return 3;
	}
	
	struct sockaddr_in addr;
	memset(&addr, 0, sizeof(addr));
	addr.sin_family = AF_INET;
	addr.sin_port = htons(port);
	addr.sin_addr.s_addr = htonl(INADDR_ANY);

	if (bind(s, (struct sockaddr*)&addr, sizeof(addr))==-1) {
		perror("bind");
		return 3;
	}
	if (listen(s, 5)==-1) {
		perror("listen");
		return 4;
	}

	fprintf(stderr, "%s start to listen on the port %d...\n", argv[0], port);

	int soc;
	struct sockaddr_storage ss;
	pthread_t th;
	socklen_t slen = sizeof(ss);
	while ((soc=accept(s, (struct sockaddr*)&ss, &slen))!=-1) {
		if ((errno=pthread_create(&th, NULL, doSession, (void*)soc))!=0) {
			perror("pthread_create");
			return 5;
		}
		pthread_detach(th);
	}
	return 6;
}
