/*
 *	Copyright (C) 1992  TGV, Inc.
 *
 *	Program (usually run at LOGIN time) to determine of the
 *	current user has new mail.
 *
 */
#include "mm_header.h"
#include <stdio.h>

main(argc,argv)
char *argv[];
{
	int fd;
	register char *cp,*cp1;
	register int i;
	int Text_Offset;
	struct Header_File_Header Header;
	struct Msg Msg;
	register struct Msg *Msgs;
	char *Text;
	char Local[256], MM_Mail_File[128];

	/*
	 *	Open the header cache file
	 */
	cp = (char *)getenv("MULTINET_MM_MAIL_FILE");
	if (!cp)
		strcpy(MM_Mail_File, "MAIL.TXT");
	else
		strcpy(MM_Mail_File, cp);
	sprintf(Local, "SYS$LOGIN:$HDRS$%s", MM_Mail_File);
	fd = open(Local, 0, 0, "shr=get", "shr=put", "shr=upd");
	if (fd < 0) {
		/*
		 *	Can't open: fall back to MAIL.TXT if we were looking
		 *	at MULTINET_MM_MAIL_FILE.
		 */
		if (cp) {
			strcpy(MM_Mail_File, "MAIL.TXT");
			sprintf(Local, "SYS$LOGIN:$HDRS$%s", MM_Mail_File);
			fd = open(Local, 0, 0, "shr=get", "shr=put", "shr=upd");
			if (fd < 0) exit(1);
		}
	}
	/*
	 *	Read in the header file header
	 */
	if (read(fd,&Header,sizeof(Header)) != sizeof(Header)) {
		close(fd);
		exit(1);
	}
	/*
	 *	Seek to the last message header and read it in
	 */
	if (lseek(fd,-sizeof(struct Msg),2) < 0) {
		close(fd);
	}
	if (read(fd,&Msg,sizeof(Msg)) != sizeof(Msg)) {
		close(fd);
		exit(1);
	}
	/*
	 *	Check for UNSEEN
	 */
	if (!(Msg.Flags & MSG_SEEN) && (Msg.Date >= Header.Last_Read)) {
		/*
		 *	Make sure there is a good FROM offset
		 */
		if (Msg.From_Size == 0) goto New_Mail1;
		/*
		 *	Read in the entire header file
		 */
		i = Header.Number_Of_Messages * sizeof(struct Msg);
		Msgs = (struct Msg *)malloc(i);
		if (Msgs == 0) goto New_Mail1;
		lseek(fd,sizeof(Header),0);
		if (read(fd,Msgs,i) != i) goto New_Mail1;
		/*
		 *	Calculate the text file offset
		 */
		Text_Offset = 0;
		i = Header.Number_Of_Messages - 1;
		while(--i >= 0)
			Text_Offset += Msgs[i].Real_Size;
		/*
		 *	Open the text file and get the message
		 */
		close(fd);
		sprintf(Local, "SYS$LOGIN:%s", MM_Mail_File);
		fd = open(Local, 0, 0, "shr=get","shr=put","shr=upd");
		if (fd < 0) goto New_Mail1;
		if (lseek(fd,Text_Offset,0) != Text_Offset) goto New_Mail1;
		i = Header.Number_Of_Messages-1;
		Text = (char *)malloc(Msgs[i].Real_Size);
		if (read(fd,Text,Msgs[i].Real_Size) != Msgs[i].Real_Size)
			goto New_Mail1;
		Text += Msgs[i].From_Offset;
		Text[Msgs[i].From_Size] = 0;
		/*
		 *	Get the FROM field to print
		 */
		cp = (char *)strchr(Text,'<');
		if (cp != 0) {
			cp++;
		} else {
			cp = Text;
			while(*cp &&
			      ((*cp == ' ') || (*cp == '\t'))) cp++;
		}
		if (*cp == 0) goto New_Mail1;
		cp1 = (char *)strchr(cp,'>');
		if (cp1 != 0) *cp1 = 0;
		/*
		 *	Print it
		 */
		printf("[You have MM mail from %s]\n",cp);
	}
	if (fd >= 0) close(fd);
	exit(1);

New_Mail1:
	printf("        You have new MM mail.\n");
	if (fd >= 0) close(fd);
	exit(1);

}
