#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include <linux/socket.h>

int main()
{
	int sock;
	uint16_t port=2234;
	struct sockaddr_in server, client;
	size_t size;
	char message[1500];
	char buf[1500];
	int len, i;
	fd_set active_fd_set, read_fd_set;
	FILE *f;

	sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
	if( sock == -1 )
	{
		printf("Error create socket\n");
		exit(0);
	}

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

	if( bind( sock, (struct sockaddr*) &server, sizeof(server)) == -1 )
	{
		printf("Error bind socket %d\n", errno);
		exit(0);
	}

	if (listen (sock, 1) < 0)
	{
		printf("Error listen socket %d\n", errno);
		exit(0);
	}

	FD_ZERO (&active_fd_set);
	FD_SET (sock, &active_fd_set);

	while(1)
	{

		read_fd_set = active_fd_set;
		if (select (FD_SETSIZE, &read_fd_set, NULL, NULL, NULL) < 0)
  		{
			printf("Error select socket %d\n", errno);
			exit(0);
		}

		/* Service all the sockets with input pending. */
		for (i = 0; i < FD_SETSIZE; ++i)
 		 if (FD_ISSET (i, &read_fd_set))
		 {
		      if (i == sock)
		      {
		           /* Connection request on original socket. */
		           int new;
		           size = sizeof (client);
		           new = accept (sock, (struct sockaddr *) &client, &size);
		           if (new < 0)
		           {
	                       printf("Error accept socket %d\n", errno);
			       exit(0);
 	                   }
		           printf ("Server: connect from host.\n" );
 	                   FD_SET (new, &active_fd_set);
	              }
	              else
		      {
			len = read (i, message, 1500);
//			len = recv (i, message, 1500, MSG_OOB);
			if( len > 0 )
			{
				printf ("Server: got message: %s\n", message);
				message[strlen(message)-1]='\0';
				strcat( message, " > res" );
				printf ("Server: execute command: %s\n", message);
				system( message );
				f=fopen("res","r");
				message[0]='\0';
				while(!feof(f))
				{
					fgets(buf, 1500, f);
					strcat(message,buf);
				}
				len = strlen(message)+1;
				len = write (i, message, len );
				if( len < 0 )
				{
					printf("Error send response\n");
					exit(0);
				}
			}
			else if( len < 0 )
			{
				printf("Error receive message\n");
				exit(0);
			} else
			{
				printf ("Server: disconnect from host.\n" );
				close (i);
			        FD_CLR (i, &active_fd_set);
			}

		      }
		}
	}
}





