/*
 * client.c - a test program for sockets
 */

#include <stdio.h>
#include <sys/types.h>
#include <fcntl.h>
#include <ctype.h>
#include <errno.h>

#define CR		'\015'
#define LF		'\012'
#define CRLF		"\015\012"
#define EOM             ".\015\012"
#define SOCKBUF		4096

char	outbuf[SOCKBUF];
char	inbuf[SOCKBUF];

char	*host, *port;

main(argc, argv)
int	argc;
char	*argv[];
{
	extern int		errno;

	int	sock, oncethru = 0;
	int	red, inlen, sockflags;

	host = argc < 2 ? "bloom-beacon" : argv[1];
	port = argc < 3 ? "nntp" : argv[2];

	sock = inet_establish_connection(host, port);
	if (sock < 0) {
		puts("Fatal error: could not establish connection.");
		exit(1);
	}
		
	inlen = 1;
	sockflags = fcntl(sock, F_GETFL);

	for (;;) {
		while ((red = read(sock, inbuf, sizeof(inbuf))) > 0) {

			write(1, inbuf, red);

			if (!oncethru++)
				if (fcntl(sock, F_SETFL, sockflags | FNDELAY) == -1)
					perror("fcntl");

			if (red<4 || !strncmp(&inbuf[red - 3],".\015\012", 3))
				break;

		}

		if (red < 0 && errno == EWOULDBLOCK)
			printf("[block] ");
		else if (red <= 0) {
			if (red)
				perror("read");
			else
				puts("Connection closed.");
			exit(1);
		}

		if ((inlen = getline(outbuf)) < 0)
			break;

		if (*outbuf != '\n')
			if (write(sock, outbuf, inlen) < 0)
				perror("socket write"), exit(1);
	}
	close(sock);
	exit(0);
}

getline(data)
char	*data;
{
	int	red;

	do {
		printf("%s %s: ", host, port), fflush(stdout);
		red = read(0, data, SOCKBUF);
	} while (red <= 0); /* && isspace(*data)); */

	if (red <= 0) {
		perror("input read");
		return -1;
	}

	return red;
}
