static char *RCSid = "$Header: service.c,v 1.7 90/04/13 12:27:42 mr-frog Exp $";

/*
 * service.c
 *
 * service a candidate socket by reading all the
 * commands and executing the right routines.
 *
 * Dave Pare, 1986
 */

#include "misc.h"
#include "proto.h"
#include "login.h"

#include <netinet/in.h>
#include <errno.h>

struct	fn {
	int	(*func)();
	char	*name;
	int	value;
};

extern	int quit();
extern	int coun();
extern	int pass();
extern	int user();
extern	int play();
extern	int list();
extern	int wat();
extern  int killpl();

struct fn fnlist[] = {
	{ user,	"user",		USER,},
	{ coun,	"coun",		COUN,},
	{ quit,	"quit",		QUIT,},
	{ pass,	"pass",		PASS,},
	{ play,	"play",		PLAY,},
	{ list,	"list",		LIST,},
	{ wat,	"wat",		WAT,},
	{ killpl,"kill",	KILL,},
	{ 0,	"",		0,},
};

/*ARGSUSED*/
service(iop, op, assoc)
	iop_t	iop;
	int	op;
	char	*assoc;
{
	struct	candidate *cp = (struct candidate *) assoc;
	char	buf[80];
	char	space[255];
	char	*argp[40];
	int	n;

	while (io_gets(iop, buf, sizeof(buf)) >= 0) {
		n = parse(buf, argp, 0, space, 0);
		if (callfn(cp, n, argp) > 0)
			return;
	}
	if (io_error(cp->iop) || io_eof(cp->iop))
		cd_delete(cp);
}

int
callfn(cp, argc, argv)
	struct	candidate *cp;
	int	argc;
	char	**argv;
{
	extern	int iswatching;
	struct	fn *fp;
	int	n;

	if (argc < 1)
		return 0;
	for (fp = fnlist; fp->func != 0; fp++) {
		if (strcmp(fp->name, argv[0]) == 0)
			break;
	}
	if (fp->func == 0) {
		sendclient(cp->iop, C_BADCMD, "command %s not found", argv[0]);
		return 0;
	}
	cp->cmd = fp->name;
	n = fp->func(cp, argv[1]);
	if (iswatching)
		dowatch();
	return n;
}

dowatch()
{
	struct	candidate *cp;

	cp = 0;
	while (cp = cd_next(cp)) {
		if (cp->state == STAT_WATCH)
			list(cp, 0);
	}
}
