#include <errno.h>
#include <stdio.h>
#include <sys/types.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/file.h>
#include "popper.h"

#include <sys/socket.h>
#include <hesiod.h>
#include <netdb.h>

#define MOVE_MESSAGE "/tmp/test_message"

main(int argc, char **argv)
{
	POP p;
	
	gethostname(p.myhost, sizeof(p.myhost));
	p.client = "tytso";
	check_for_move_message(&p, 0);
	
}



int
check_for_move_message(p, dfd)
	POP *p;
	int dfd;
{
	struct hes_postoffice *	hesinfo;
	struct hostent *	h;
	struct sockaddr 	s1, s2;
	char                    buffer[BUFSIZ];         /*  Read buffer */
	char			*cp, *ats;
	FILE *			f;
	
	hesinfo = hes_getmailhost(p->client);
	if (!hesinfo || strcmp(hesinfo->po_type, "POP"))
		return (-1);

	/*
	 * Compare the address of the user's POP server with our
	 * address.  If they match, then the user is using the right
	 * mail server.  If they don't, then send them a message...
	 */
	if (!(h = gethostbyname(hesinfo->po_host)))
		return -1;
	memset(&s1, 0, sizeof(s1));
	s1.sa_family = h->h_addrtype;
	memcpy((char *)&s1.sa_data, h->h_addr, h->h_length);
	
	if (!(h = gethostbyname(p->myhost)))
		return -1;
	memset(&s2, 0, sizeof(s1));
	s2.sa_family = h->h_addrtype;
	memcpy((char *)&s2.sa_data, h->h_addr, h->h_length);
	
	if ((s1.sa_family == s2.sa_family) &&
	    memcmp(s1.sa_data, s2.sa_data, sizeof(s1.sa_data)) == 0)
		return -1;

	/*
	 * OK, the user must be on a different server.  Let's send her
	 * a special message....
	 */
	if ((f = fopen(MOVE_MESSAGE, "r")) == NULL)
		return -1;
	while (fgets(buffer, sizeof(buffer), f)) {
		cp = buffer;
		while ((ats = strchr(cp, '@'))) {
			*ats++ = '\0';
			write(dfd, cp, strlen(cp));
			if (*ats == 'H')
				write(dfd, hesinfo->po_host,
				      strlen(hesinfo->po_host));
			else if (*ats == 'O')
				write(dfd, p->myhost, strlen(p->myhost));
			else 
				write(dfd, ats, 1);
			if (*ats)
				ats++;
			cp = ats;
		}
		write(dfd, cp, strlen(cp));
	}
	fclose(f);
	return 0;
}
