/* client.c */

#include<sys/socket.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<netinet/in.h>
#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
#include<fcntl.h>

main(int argc,char *argv[])
{
   int sd, i = 0, authenticated = 0, count = 0, fd = 0, n = 0, j = 0;
   int bufsize = 50, quit = 0, match = 0, pos = 0, found = 0;
   char *buffer = malloc(bufsize), c, choice, filename[30], temp[6];
   struct sockaddr_in address;
   struct stat buf;
   

   if(argc != 2)
	{
	printf("Usage : %s <IP Address>\n", argv[0]);
	exit(-1);
	}

   printf("\x1B[2J");

   if ((sd = socket(AF_INET,SOCK_STREAM,0)) > 0)
	printf("The Socket was created\n");
   else
	{
	printf("Error creating the Socket...exiting !!\n");
	exit(-1);
	}

   address.sin_family = AF_INET;
   address.sin_port = htons(15000);
   inet_pton(AF_INET,argv[1],&address.sin_addr);
   
   printf("Calling Connect....\n");
   if (connect(sd,(struct sockaddr *)&address,sizeof(address)) == 0)
	printf("The connection was accepted with the server %s...\n",inet_ntoa(address.sin_addr));
   else
	{
	printf("Error creating the Socket...exiting !!\n");
	exit(-1);
	}
   getc(stdin);
   i = 0;
   authenticated = 0;
   while(i < 3)
	   {
	   buffer[0] = 'u';
	   buffer[1] = ' ';
	   buffer[2] = '\0';
	   system("clear");
	   printf("\n\nPlease enter the UserName - ");
	   gets(&buffer[2]);
	   send(sd, buffer, bufsize, 0);
	   recv(sd, buffer, bufsize, 0);

//printf("%s\n",buffer);

	   	if(!strcmp(buffer, "<SUC>"))
	   	{
	   	buffer[0] = 'p';
	   	buffer[1] = ' ';
	   	buffer[2] = '\0';
	   	printf("\n\nPlease enter the Password - ");
	   	gets(&buffer[2]);
	   	send(sd, buffer, bufsize, 0);
	   	recv(sd, buffer, bufsize, 0);

	//printf("%s",buffer);

	   		if(!strcmp(buffer, "<SUC>"))
			   {
			    authenticated = 1;
			    break;
			   }
	   	}
		printf("\nInvalid UserName or Password !!\n");
	   	i++;
	   }

	   if (!authenticated)
		   {
		   printf("Invalid User tries - 3 times...Exiting\n");
		   getc(stdin);
		   strcpy(buffer, "q<EOC>");
		   send(sd, buffer, 7, 0);
		   close(sd);
		   exit(-1);
		   }

   do	{
	system("clear");
	printf("\n\nMenu...\n1. List Directory  \n2. Read file \n3. Write file \n4. Quit \n");
	//fflush(stdin);
	printf("\nPlease enter your choice - ");
	choice = getchar();
	printf("\nSending choice - %c\n", choice);
	//getc(stdin);
	switch(choice)
	{
		case '1':
			system("clear");
			printf("\nCASE - 1\n");
			printf("--------\n");
			strcpy(buffer, "l<EOC>");
			match = 0;
			found = 0;
			pos = 0;
			send(sd, buffer, 7, 0);
			recv(sd, buffer, bufsize, 0);
			if( !strcmp(buffer,"<ERR>") )
			{
				printf("Error received from server...\n");
				break;
			}
			else
			{
				printf("\n");
				do
				{ 
			      	n = recv(sd, buffer, bufsize, 0);
				//printf("\nn = %d\n",n);
				//for(j=0;j<n;j++)
					//printf("%c",buffer[j]);
				//printf("%s",buffer);
				if(match == 1)
				{ 
					for(j=pos; j<6; j++)
						temp[j] = buffer[j-pos];
					if(!strcmp(temp, "<EOF>"))
					{ 
						break;
					}
					match = 0;
				}
				//getc(stdin);
				for(j=0;j<n;j++)
				{ 
				if(buffer[j] == '<')
				{ 
					strncpy(temp, &buffer[j], n-j);
					if((n-j) < 6)
						{
						match = 1;
						pos = n-j;
						}
					else
						if(!strcmp(temp, "<EOF>"))
							{
							found = 1;
							match = 0;
							break; 
							}
				}
			else
				printf("%c",buffer[j]);
				}
			if (found)
				break;
				
				//if((buffer[n-6] == '<') && (buffer[n-5] == 'E') && (buffer[n-4] == 'O') && (buffer[n-3] == 'F') && (buffer[n-2] == '>') && (buffer[n-1] == '\0'))
					//break;
				}
				while(1);
			getc(stdin);
			}
			break;

		case '2':
			system("clear");
			printf("\nCASE - 2\n");
			printf("--------\n");

			while(1)
				{
				buffer[0] = 'r';
				buffer[1] = ' ';
				buffer[2] = '\0';

				printf("Please enter the Filename or 'q' to return to the Main Menu:- ");

				count = 0;
				match = 0;
				found = 0;
				pos = 0;
				j = 0;

					scanf("%s", filename);	
					getc(stdin);
					printf("\nFileName - %s\n", filename);
					strcpy(&buffer[2], filename);
					printf("\nBuffer - %s\n", buffer);

				if(buffer[2] == 'q' && buffer[3] == '\0')
					break;
				count = strlen(buffer);
				strcpy(&buffer[count+1], "<EOC>");	
					//printf("\nBuffer - %s\n", buffer);
				send(sd, buffer, count+7, 0);
				recv(sd, buffer, bufsize, 0);

				if( !strcmp(buffer,"<ERR>") )
					{
					printf("Error received from server\n...");
					break;
					}
				else
					{
					if( (fd = open(filename, O_CREAT|O_TRUNC|O_RDWR)) < 0)
						printf("....error opening file - %s....\n", filename);
						do
						{ 
				if(match == 1)
					{ 
					for(j=pos; j<6; j++)
						temp[j] = buffer[j-pos];
					match = 0;
					}
				n = recv(sd, buffer, bufsize, 0);
				for(j=0;j<n;j++)
				{ 
				if(buffer[j] == '<')
				{ 
					strncpy(temp, &buffer[j], n-j);
					if((n-j) < 6)
						{
						match = 1;
						pos = n-j;
						}
					else
						if(!strcmp(temp, "<EOF>"))
							{
							found = 1;
							match = 0;
							}
				}
				}
						if(match)
							{
							write(fd,buffer,n-pos);
							printf("\nMATCH CASE\n");
							break;
							}
						else if (found)
							{
							write(fd,buffer,n-6);
							printf("\nFOUND CASE\n");
							break;
							}
						else
							write(fd,buffer,n);
						}
						while(1);
					close(fd);
					printf("Received File - %s\n", filename);
					getc(stdin);
					}
				}
			break;

		case '3':
			system("clear");
			printf("\nCASE - 3\n");
			printf("--------\n");

			while(1)
				{
				buffer[0] = 'w';
				buffer[1] = ' ';
				buffer[2] = 'q';
				buffer[3] = '\0';

				printf("Please enter the Filename or 'q' to return to the Main Menu:- ");

				count = 0;
				scanf("%s",filename);
				getc(stdin);
				fflush(stdin);
				strcpy(&buffer[2], filename);
				count = strlen(buffer);

				if( buffer[2] == 'q' && buffer[3] == '\0' )
					break;

				if( stat(filename, &buf) < 0 )
					{
					printf("\nError - File doesn't exist...\n");
					continue;
					}

				strcpy(&buffer[count+1], "<EOC>");	
				send(sd, buffer, count+7, 0);
				recv(sd, buffer, bufsize, 0);
				printf("status frm server - %s", buffer);
				if( !strcmp(buffer,"<ERR>") )
					{
					printf("Error received from server\n...");
					break;
					}
				else
					{
					fd = open(filename, O_RDONLY);
						do
						{ 
					      	n = read(fd,buffer,bufsize);
						send(sd,buffer,n,0);
						}
						while(n==bufsize);
					send(sd,"<EOF>",6,0);
					close(fd);
					printf("Sent File - %s\n", filename);
					}
				}
			getc(stdin);
			break;

		case '4':
			system("clear");
			printf("\nCASE - 4\n");
			printf("--------\n");

			printf("\nExiting...closing the socket !!\n");
			strcpy(buffer, "q<EOC>");
			send(sd, buffer, 7, 0);
			close(sd);
			exit(0);
			break;

		default :printf("\nError....Wrong Choice !!\n");
			break;
  	}

  }
   while (1);
}
//}

