// Mailfixf.cpp - Program to Process incoming information from FXUUCICO

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void process1(void);
void find_name(void);


// out  is used to output the updated message files
// out2 is used to output the batch file OUTPUT.BAT
// to move the mail to the home mailboxes
FILE *out, *out2;
// a - Global Line used by main and process file buffers
char a[2048], bufr[2048], bufr2[2048], bufr3[2048], b[2048], n[32];
char athost[40],hostexclaim[40],hostexclaim2[40],postmaster[40];

// main requires the local host name
void main(void)
{
	FILE  *in;		// File for getting filenames
	int j;
	char ch;
	char HostName[60]="NOT-DEFINED"; 				// LOCAL HOST NAME
	char FullName[60]="NOT-DEFINED";        			// FULL HOST AND LOCAL

	// Program uses Host.Dat file for storing Information about Host and timezone
	// Format is 3 lines:
	// HOST:  local name   Example:  HOST:  GCCcc
	// FULL:  full host              FULL:  GCCcc.Guam.Net
	// TIME:  timezone               TIME:  GST +1400
	// ORGAN: organization           ORGAN: Guam Community College Computer Center
	// POST:  postmaster             POST:  MICHAEL
	// The keywords must be in ALL caps and Left justified including the :
	// The values can have spaces before and/or after them
	// Any lines with other values are ignored.
	// Information can be in any order.
	// File goes in the Spool directory

	// Open File
	if ((in = fopen("HOST.DAT","r")) == NULL)
	{
		fprintf(stderr,"Open of Host file Host.Dat failed\n");
		exit(1);
	}
	// Read Host Information from File
	while (!feof(in))
	{
		j=0;						// Initialize Array Pointer to Beginning
		while(((ch=fgetc(in))!='\n') && !feof(in))	// Read Characters till End of Line or End of File
			a[j++]=ch;				// Store Character
		a[j]=NULL;					// Add NULL to end of String
		if (strstr(a,"HOST:")!=0)      			// Check for HOST: Line
			strcpy(HostName,&a[5]);            	// If Yes, copy Information after HOST:
		if (strstr(a,"FULL:")!=0)			// Check for FULL: Line
			strcpy(FullName,&a[5]);                 // If Yes, copy Information after FULL:
		if (strstr(a,"POST:")!=0)			// Check for POST: Line
			strcpy(postmaster,&a[5]);               // If Yes, copy Information after POST:
	}
	fclose(in);						// Close file

	// Trim Trailing blanks for fields
	while (HostName[strlen(HostName)-1]==' ')			HostName[strlen(HostName)-1]=NULL;
	while (FullName[strlen(FullName)-1]==' ')                       FullName[strlen(FullName)-1]=NULL;
	while (postmaster[strlen(postmaster)-1]==' ')                   postmaster[strlen(postmaster)-1]=NULL;

	// Trim Leading blanks from fields
	while (HostName[0]==' ')					strcpy(HostName,&HostName[1]);
	while (FullName[0]==' ')                                        strcpy(FullName,&FullName[1]);
	while (postmaster[0]==' ')                                      strcpy(postmaster,&postmaster[1]);

	// Create Variables used to find Users Name
	// HostName is used for format MICHAEL@GCCCC.GUAM.NET
	strupr(HostName);            	// GCCCC
	strcpy(athost,"@");           	// Create @host name
	strcat(athost,HostName);	// @GCCCC.GUAM.NET
	// Host exclaim is for format NET!GUAM!GCCCC!MICHAEL
	strcpy(hostexclaim,HostName);   // Create !host name
	strcat(hostexclaim,"!");        // GCCCC!

	strupr(FullName);           	// GCCCC.GUAM.NET
	// Host exclaim2 is for format GCCCC.GUAM.NET!MICHAEL or
	//                      format GCCCC.GUAM.NET!MICHAEL!KUENTOS.GUAM.NET
	strcpy(hostexclaim2,FullName);
	strcat(hostexclaim2,"!");	// GCCCC.GUAM.NET!

	// Open Input file: File is a Directory of *.D files Redirected to File
	if ((in = fopen("temp.$$$", "rt")) == NULL)
	{
		fprintf(stderr, "Cannot open input file.\n");
		exit(1);
	}
	if (setvbuf(in, bufr2, _IOFBF, 2048) != 0)		// Open a Input File Buffer
		printf("failed to set up buffer for input file\n");
	// Open Output file to create batch file for moving Mail
	if ((out2 = fopen("OUTPUT.bat", "wt")) == NULL)
		fprintf(stderr, "Cannot open output file.\n");

	// Read until End of File
	while (!feof(in))
	{
		j=0;						// Initialize Array Pointer to Beginning
		while(((ch=fgetc(in))!='\n') && !feof(in))	// Read Characters till End of Line or End of File
		{
			a[j++]=ch;				// Store Character
		}
		a[j]=NULL;					// Add NULL to end of String
		if (a[9]=='D')					// Check if Line Read has D as file extension
			process1();				// Process the File Name from Line
	}
	fclose(in); 						// Close Input File
	fprintf(out2,"IF EXIST TEMP.$$$ DEL TEMP.$$$\n");
	fprintf(out2,"FXCLEAN\n");				// Batch file for final Clean Up
	fclose(out2);
}

// Routine to Process the File to make corrections if necessary
// Process will put Quotes around From Name if they were not originally
// included. Without the Quotes, the Pegasus mail reply will not work properly.
// From: John Doe <address>
// From: "John Doe" <address>
// The Program will also wrap lines that are longer than 80 character, and
// occur after the To: line, so routing lines are not changed.
void process1(void)
{
	FILE  *in1;
	char f[15], g[15], x[15], ch;
	int i, j, y;
	i=0;						// Initialize Variable
	n[0]=NULL;					// Set n string to NULL
	while (a[i]!=' ')				// Copy Letters from line of Input file
	{						// to File name String
		f[i]=a[i];
		i++;
	}
	f[i]=NULL;					// Add NULL to terminate string
	strcpy(x,f);
	strcat(x,".X");
	strcat(f,".D");					// Append File Extension
	strcpy(g,f);					// Copy F Filename String to G File Name String
	strcat(g,"XX");					// Add XX to G Filename extension
	// f  is the name of the file to process
	// g  is the processed file.
	// f  is read. filename.z
	// g  is the processed output of f. filename.z to filename.zxx

	if ((out = fopen(g, "wt")) == NULL)			// Open Output file
	{                                                	// filename.zxx
		fprintf(stderr, "Cannot open output file.\n");
		exit(1);
	}
	if (setvbuf(out, bufr3, _IOLBF, 2048) != 0)
		printf("failed to set up buffer for output file\n");

	if ((in1 = fopen(x, "rt")) == NULL)			// Open Input file
	{							// filename.z (Current Directory)
		fprintf(stderr, "Cannot open input file.\n");
		exit(1);
	}
	if (setvbuf(in1, bufr, _IOFBF, 2048) != 0)		// Open a Input File Buffer
		printf("failed to set up buffer for input file\n");

	while (!feof(in1))			// Process Mail Message till End of File
	{
		j=0;				// Initialize Pointer
		while(((ch=fgetc(in1))!='\n') && !feof(in1))	// read characters till End of Line
		{						// or End of File
			a[j]=ch;				// Store Character
			j++;					// Increment Counter
		}
		a[j]=NULL;					// Terminate String
		if (strstr(a,"C rmail")!=0)
		{
			strcpy(b,&a[8]);
			if (strstr(b,"@")==0 && strstr(b,"!")==0)
			{
				strupr(b);
				strcpy(n,b);
			}
			else
			{
				strupr(b);
				find_name();
			}
		}
	}
	fclose(in1);
	if ((in1 = fopen(f, "rt")) == NULL)			// Open Input file
	{							// filename.z (Current Directory)
		fprintf(stderr, "Cannot open input file.\n");
		exit(1);
	}
	if (setvbuf(in1, bufr, _IOFBF, 2048) != 0)		// Open a Input File Buffer
		printf("failed to set up buffer for input file\n");

	while (!feof(in1))			// Process Mail Message till End of File
	{
		j=0;				// Initialize Pointer
		while(((ch=fgetc(in1))!='\n') && !feof(in1))	// read characters till End of Line
		{						// or End of File
			a[j]=ch;				// Store Character
			j++;					// Increment Counter
		}
		a[j]=NULL;					// Terminate String
		strncpy(b,a,5);					// Copy First 5 characters
		// Check if Line is the From: Line
		// Check if Line already has '"'
		// Check if Line has a '<' in it
		// I have only seen this problem in lines with <address>
		if (strstr(b,"From:")!=0 && strstr(a,"<")!=NULL)
		{
			while(a[6]==' ')     			// Trim Blanks between From:
				strcpy(&a[6],&a[7]);
			if (a[6]!='"' && a[6]!='<')		// Check if already have "
			{
				strcpy(b,"From: "); 			// Copy "From: " to b string
				b[6]='"';				// Insert "
				j=7;                       		// Set pointer
				for(i=6;i<=strlen(a);i++)		// Copy rest of Line
				{
					if (a[i]=='<')			// Check for '<' of address
					{
						b[j-1]='"';  		// Add Ending "
						b[j]=' ';               // Add Space
						j++;                    // Increment Pointer
					}
					b[j]=a[i];			// Copy character from a to b
					j++;                 		// Increment Pointer
				}
				strcpy(a,b);				// Copy corrected b string to a
			}
		}
		strcpy(b,a);					// Copy a string to b string

// This Section finds the Name of the user the mail is address To:
// It scans fo the FOR in the header lines or
// For the TO: line if not found ealier
		strupr(b);             				// Conver to Upper case
		if ((strstr(b,"TO:")!=NULL ||			// Check for To: Line
		     strstr(b,"FOR")!=NULL) &&			// Check for FOR Line
		     n[0]==NULL)                                // Don't bother if Name already found
			    find_name();


		strcpy(b,a);					// Reset b to a string (Not all caps)
		if (!feof(in1) || strlen(b)>1)			// Print line to Screen and File
		{						// If not End of File
			printf("%s\n",b);                    	// or strlen(b)>1
			fprintf(out,"%s\n",b);                  // This elimanates adding a blank line if
		}                                    		// End file marker is on a separate line
	}
	fclose(in1);						// Close Input File
	fclose(out);						// Close Output File
	strcpy(a," ");
	if (n[0]==NULL)
	{
		strcpy(n,postmaster);				// Postmaster Name if Name not Found
		strcpy(a,"No Name");
	}
	// Call Movemail Batch file with filename postmaster name
	fprintf(out2,"CALL MOVEMAIL %s %s %s %s\n",g,postmaster,n,a);
}

void find_name(void)
{
	char c[256], *p;
	int y;
	p=strstr(b,athost);			// Search for @ type Address
	if (p!=NULL)				// If Found
	{
		strcpy(p,"\0");               	// Put NULL at @ position to truncate string
		strcpy(c,b);			// Copy truncated string
		y=strlen(c);
		while (c[y]!=' ' &&		// Look from last position
		       c[y]!=':' &&         	// Until we find one of these
		       c[y]!='<' &&		// Characters
		       y>=0)
				y--;		// Decrement pointer
		y++;				// Move the Pointer up one
		p=&c[y];			// Set Pointer to that character
		strcpy(n,p);			// Copy from that point to end of string (NAME)
	}
	else
	{
		p=strstr(b,hostexclaim);		// If @ address not found, check for ! address
		if (p!=NULL)			// If ! address found
		{
			strcpy(c,(p+strlen(hostexclaim)));     	// Copy string skipping over host!
			y=2;
			while (c[y]!=',' &&	// Move pointer until
			       c[y]!='>' &&	// finding one of these characters
			       c[y]!=')' &&
			       c[y]!=' ' &&	// or finding the end of string
			       c[y]!='@' &&
			       c[y]!='!' &&
			       y<=strlen(c))
					y++;
			c[y]=NULL;		// Terminate string at that point
			strcpy(n,c);        	// Copy String to NAME
		}
		else
		{
			p=strstr(b,hostexclaim2);		// If @ address not found, check for ! address
			if (p!=NULL)			// If ! address found
			{
				strcpy(c,(p+strlen(hostexclaim2)));     	// Copy string skipping over host!
				y=2;
				while (c[y]!=',' &&	// Move pointer until
					c[y]!='>' &&	// finding one of these characters
					c[y]!=')' &&
					c[y]!=' ' &&	// or finding the end of string
					c[y]!='@' &&
					c[y]!='!' &&
					y<=strlen(c))
						y++;
				c[y]=NULL;		// Terminate string at that point
				strcpy(n,c);        	// Copy String to NAME
			}
		}
	}
}
