/*
 *	Copyright (C) 1988  SRI International
 *	Copyright (C) 1988, 1989  TGV, Incorporated
 *
 *	Deliver mail using VMSMAIL
 *
 */

#include "address.h"
#include <stdio.h>
#include <signal.h>
#include <ctype.h>
#include "vax-mm.h"
#ifdef	VMS


/*
 *	Dispatch routines for "generic" VMS delivery
 */
int Deliver_Net_Mail(Address,Header,Header_Length,Text,Text_Length)
struct Address *Address;
char *Header;
int   Header_Length;
char *Text;
int   Text_Length;
{
#ifdef MULTINET
	if (RUNNING_MULTINET) {
		return(MultiNet_Deliver_Net_Mail(Address,Header,Header_Length,
						 Text,Text_Length));
	}
#endif
#ifdef PMDF
	if (RUNNING_PMDF) {
		enable_image_privilege();
		return(PMDF_Deliver_Net_Mail(Address,Header,Header_Length,
					     Text,Text_Length));
		disable_image_privilege();
	}
#endif
#ifdef MX
	if (RUNNING_MX) {
		return(MX_Deliver_Net_Mail(Address,Header,Header_Length,
					     Text,Text_Length));
	}
#endif
	printf("ERROR:  Couldn't find a mail agent for Network Mail\n");
}



/*
 *	Deliver Local mail (this version for VMS/EUNICE mail)
 */
Deliver_Local_Mail(Address,Header,Header_Length,Text,Text_Length)
register struct Address *Address;
char *Header;
int   Header_Length;
char *Text;
int   Text_Length;
{
	FILE *f;
	int fd;
	char Filename[32];
	char Users[80];
	char Subject[32];
	char Command_Line[128];

	/*
	 *	Set the VMS mail subject field
	 */
	sprintf(Subject,"[RESENT MM-Mail]");
	/*
	 *	Create a file with the complete message text in it
	 */
	sprintf(Filename,"sys$scratch:mm%d.tmp",getpid() & 0xffff);
	fd = creat(Filename,0777);
	if (fd < 0) {
		socket_perror("temporary file");
		return;
	}
	f = fdopen(fd,"w");
	write(fileno(f),Header,Header_Length);
	write(fileno(f),Text,Text_Length);
	fclose(f);
	/*
	 *	Run through the address list
	 */
	Users[0] = 0;
	while(Address) {
		/*
		 *	See if we must flush the user list
		 */
		if ((strlen(Users) + strlen(Address->User)) > 70) {
			/*
			 *	Yes, send the mail
			 */
			sprintf(Command_Line,"$ mail %s %s /subj=\"%s\"",
				Filename,Users,Subject);
			printf(" --"); fflush(stdout);
			system(Command_Line);
			printf(" ok\n");
			Users[0] = 0;
		}
		/*
		 *	Add to the user list
		 */
		if (Users[0] == 0) {
			printf(" ");
		} else {
			printf(","); strcat(Users,",");
		}
		strcat(Users,Address->User);
		printf("%s",Address->User);
		fflush(stdout);
		/*
		 *	Get the next address
		 */
Next:		Address = Address->Next_Address;
	}
	/*
	 *	Flush the last addresses
	 */
	if (Users[0] != 0) {
		sprintf(Command_Line,"$ mail %s %s /subj=\"%s\"",
			Filename,Users,Subject);
		printf(" --"); fflush(stdout);
		system(Command_Line);
		printf(" ok\n");
	}
	/*
	 *	Delete the temporary file
	 */
	unlink(Filename);
}


/*
 *	End of all delivery (for system dependent code, like UNIX, that needs
 *				to gather up ALL the recipients before doing
 *				the delivery)
 */
Deliver_Done()
{
	/* For VMS this is a NO-OP */
	return;
}

#endif	VMS
