#include "global.h"
#if defined(CALLCLI) || defined(SAMCALLB) || defined(QRZCALLB)
#include "commands.h"
#include "mbuf.h"
#include "socket.h"
#include "session.h"
#include "netuser.h"

#if !defined(_lint)
static char rcsid[] OPTIONAL = "$Id: callcli.c,v 1.13 1997/06/28 16:46:13 root Exp $";
#endif

extern char *Callserver;


int
docallbook (argc, argv, p)
int argc;
char *argv[];
void *p OPTIONAL;
{
struct sockaddr_in sock;
char const *cp;
int s, i;
struct mbuf *bp;
struct session *sp;

	/* Allocate a session descriptor */
	if ((sp = newsession (argv[1], FINGER, 0)) == NULLSESSION) {
		tputs (TooManySessions);
		(void) keywait (NULLCHAR, 1);
		return 1;
	}
	if (Callserver == NULLCHAR) {
		tputs ("Callbook Services Not Configured.\n");
		(void) keywait (NULLCHAR, 1);
		freesession (sp);
		return 1;
	}
	sp->ttystate.echo = sp->ttystate.edit = 0;
	sp->flowmode = 1;
	sock.sin_family = AF_INET;
#ifndef newcode
	sock.sin_port = IPPORT_CALLDB;
#else
	sock.sin_port = IPPORT_FINGER;
#endif
	for (i = 1; i < argc; i++) {
		cp = Callserver;
		(void) strupr (argv[i]);
		tprintf ("Looking up \"%s\" in the callbook at %s\n", argv[i], cp);
		if ((sock.sin_addr.s_addr = resolve (cp)) == 0) {
			tprintf ("Callserver %s unknown\n", cp);
			continue;
		}
		tprintf ("trying %s", psocket ((struct sockaddr *) &sock));
		if ((sp->s = s = socket (AF_INET, SOCK_STREAM, 0)) == -1) {
			tputs ("Can't create socket\n");
			break;
		}
		(void) sockmode (s, SOCK_ASCII);
		if (connect (s, (char *) &sock, sizeof (sock)) == -1) {
			cp = sockerr (s);
			tprintf (" -- Connect failed: %s\n", cp != NULLCHAR ? cp : "");
			close_s (s);
			sp->s = -1;
			continue;
		}
		tputc ('\n');
		usprintf (s, "%s\n", argv[i]);
		usflush (Curproc->output);
		while (recv_mbuf (s, &bp, 0, NULLCHAR, (int *) 0) > 0)
			(void) send_mbuf (Curproc->output, bp, 0, NULLCHAR, 0);
		close_s (s);
		sp->s = -1;
	}
	(void) keywait (NULLCHAR, 1);
	freesession (sp);
	return 0;
}

#endif /* CALLCLI */
