/* Svolge il lavoro usuale del client ma invoca shutdown */

#include	"basic.h"

void client_echo_shutdown(FILE *fp, int sockfd);

int main(int argc, char **argv) {
	int			sockfd, n;
	struct sockaddr_in	servaddr;

	if (argc != 3){
		printf("usage: echocli <IPaddress> <PORT>\n");
		exit(1);
}
	if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
		printf("socket error\n");
		exit(1);
	}

	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_port   = htons(atoi(argv[2]));	/* echo server */
	if (inet_pton(AF_INET, argv[1], &servaddr.sin_addr) <= 0){
		printf("inet_pton error for %s", argv[1]);
		exit(1);
	}

	if (connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0){
		printf("connect error\n");
		exit(1);
	}

        client_echo_shutdown(stdin, sockfd);	/* svolge tutto il lavoro del client */

	exit(0);
}

void client_echo_shutdown(FILE *fp, int sockfd) {
        int     maxfdl, stdineof;
        fd_set  rset;
        char    sendline[MAXLINE], recvline[MAXLINE];
        int     n;

        FD_ZERO(&rset);
        for( ; ; ) {

            FD_SET(fileno(fp), &rset);
            FD_SET(sockfd, &rset);
            maxfdl = MAX(fileno(fp), sockfd) + 1;
            if( select(maxfdl, &rset, NULL, NULL, NULL) < 0 ){
                printf("select error\n");
		exit(1);
	    }

            if( FD_ISSET(sockfd, &rset) ) {
                if ( (n = reti_readline(sockfd, recvline, MAXLINE)) < 0) {
                     if( errno == EPIPE ) {
                         printf("%s [%d]: server terminated prematurely\n",__FILE__,__LINE__);
                         break;
                     }
                     else{
                         printf("readline error\n");
			 exit(1);
			}
                } 
                if (n == 0) {
                    if( stdineof == 1 )
                        return;
                    else {
                        printf("%s [%d]: server terminated prematurely\n",__FILE__,__LINE__);
                        exit(1);
                    }
                }

                fputs(recvline, stdout);
            }

            if( FD_ISSET(fileno(fp), &rset) ) {
                if( fgets(sendline, MAXLINE, fp) == NULL) {
                    stdineof = 1;
                    shutdown(sockfd, 1); /* il client non vuole piu' scrivere ma vuole ricevere i msg che il server non ha ancora inviato */
                    FD_CLR(fileno(fp), &rset);
                    continue;
                }

                if( (reti_writen(sockfd, sendline, strlen(sendline))) < 0){
                    printf("write error\n");
		    exit(1);
		}
            }
        }
}

