#ifndef lint
static char *RCSid = "$Header: /usr/brule/guest/empire/empire/emprcs/client/expect.c,v 2.1 1995/10/11 03:07:43 empire Exp $";
#endif /* not lint */

/*
 * expect.c
 *
 * read from the socket, expecting to see a particular
 * code.
 *
 */

#include "misc.h"
#include "fnlist.h"

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/socket.h>

int
expect(s, match, buf)
	int	s;
	int	match;
	s_char	*buf;
{
	int	size;
	s_char	*p;
	int	n;
	int	code;
	int	newline;
	s_char	*ptr;
	int	cc;

	size = 1024;
	(void) alarm(30);
	ptr = buf;
	n = recv(s, ptr, size, MSG_PEEK);
	if (n <= 0) {
		fprintf(stderr, "Expecting code %d\n", match);
		perror("recv");
		return 0;
	}
	size -= n;
	buf[n] = '\0';
	if ((p = strchr(ptr, '\n')) == 0) {
		do {
			cc = read(s, ptr, n);
			if (cc < 0) {
				perror("expect: read");
				return 0;
			}
			if (cc != n) {
				fprintf(stderr,
					"expect: short read (%d not %d)\n",
					cc, n);
				return 0;
			}
			ptr += n;
			if ((n = recv(s, ptr, size, MSG_PEEK)) <= 0) {
				fprintf(stderr, "Expecting %d, got %s\n",
					match, buf);
				return 0;
			}
			size -= n;
			ptr[n] = '\0';
		} while ((p = index(ptr, '\n')) == 0);
		newline = 1 + p - buf;
		*p = 0;
	} else
		newline = 1 + p - ptr;
	cc = read(s, buf, newline);
	if (cc < 0) {
		perror("expect: read #2");
		return 0;
	}
	if (cc != newline) {
		fprintf(stderr, "expect: short read #2 (%d not %d)\n",
			cc, newline);
		return 0;
	}
	buf[newline] = '\0';
	(void) alarm(0);
	if (!isxdigit(*buf)) {
		fprintf(stderr, "Expecting %d, got %s\n", match, buf);
		return 0;
	}
	if (isdigit(*buf))
		code = *buf - '0';
	else {
		if (isupper(*buf))
			*buf = tolower(*buf);
		code = 10 + *buf - 'a';
	}
	if (code == match)
		return 1;
	return 0;
}

sendcmd(s, cmd, arg)
	int	s;
	int	cmd;
	s_char	*arg;
{
	extern	struct fn fnlist[];
	s_char	buf[80];
	int	cc;
	int	len;

	(void) sprintf(buf, "%s %s\n", fnlist[cmd].name, arg != 0 ? arg : (s_char *)"");
	len = strlen(buf);
	cc = write(s, buf, len);
	if (cc < 0) {
		perror("sendcmd: write");
	}
	if (cc != len) {
		fprintf(stderr, "sendcmd: short write (%d not %d)\n", cc, len);
	}
}
