/* This thing checks socket.c for basic functionality */

#include <errno.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "socket.h"

#define	TEST_STR "wwzzzoooooooooooooooooommmmm"

void
die(char *fmt, ...) {
	va_list ap;

	va_start(ap, fmt);
	vfprintf(stderr, fmt, ap);
	va_end(ap);

	exit(1);
}

int
main(int argc, char *argv[]) {
	sock_t *sock;

	/* server */
	if (strstr(argv[0], "test1-srv")) {
		sock_t *talksock;

		sock = sock_listen("", 65432, 0);
		if (! sock)
			die("s sock_listen() failed: (%d) %s\n", errno, strerror(errno));

		if (! sock_unset_nb(sock))
			die("s sock_unset_nb() failed: (%d) %s\n", errno, strerror(errno));

		talksock = sock_accept(sock);

		if (! talksock)
			die("sock_accept() failed: (%d) %s\n", errno, strerror(errno));

		sleep(2);

		if (write(talksock->fd, TEST_STR, strlen(TEST_STR)) < 0)
			die("write() failed: (%d) %s\n", errno, strerror(errno));

		pause(); /* yawn */

		/* client */
	} else {
		char buf[1024];

		sleep(1);

		/* we assume that we managed to connect fast enough */
		sock = sock_connect("127.0.0.1", 65432, 0);
		if (! sock)
			die("c sock_connect() failed: (%d) %s\n", errno, strerror(errno));

		if (! sock_unset_nb(sock))
			die("c sock_unset_nb() failed: (%d) %s\n", errno, strerror(errno));

		/* we should now hopefully have everything arrived here.. */
		/* it's broken, but .. :-) */
		if (read(sock->fd, buf, strlen(TEST_STR)) < 0)
			die("read() failed: (%d) %s\n", errno, strerror(errno));
		buf[strlen(TEST_STR)] = 0;

		if (strcmp(buf, TEST_STR)) {
			fprintf(stderr, "%s doesn't match with %s.. wrong, man!\n", buf, TEST_STR);
			return 1;
		}
	}

	return 0;
}
