// Fillterze.cpp a program to take the output produced by Pegasus Mail/PC in standalone
// mode or from a Lan, and place it appropriately. with associated support .cmd and .xqt
// files for mail processing using the Waffle BBS uucico and uuxqt programs.
//
// Pegasus Mail/PC (C) Copyright 1990, 1991, David Harris, Dunedin, New Zealand
// WAFFLE  (C) Copyright 1991 by Darkside International of Mountain View CA.
//
// Modification Author: Michael D. Setzer II, Guam Community College, Guam
// Address: MSETZERII@cup.portal.com
// Permission is granted to do whatever you like with this code. If you do have
// problems or suggestions, please drop me a line. No warranty whatsoever is granted
// or implied, but I will attempt to make modification if information is
// forward to me and it is within my capability.

// Original Author of Filter
// Author: Brendan Murray, Dunedin, New Zealand
// Permission is granted to do whatever you like with this code. Just about
// anyone ought to be able to improve on it. No warranty whatsoever is granted
// or implied.
//
// V1.1
//
// 	Command line parameters.
// 	0:	the command
// 	1:	username
// 	2:	container file name -- full path
// 	3:	To: field for mail
// 	4:	The time in RFC 822 format  (TIME NO LONGER USED IN THIS PROGRAM)
//
// 	Actions
// 	1. Take the RFC 822 message produced by pmail and prepend a uucp acceptible From line
// 	2. Create a .cmd file to tell UUCICO what to do
// 	3. Create a .xqt file to tell UUXQT what to do at the other end
//

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <dir.h>
#include <time.h>

void main (int argc, char * argv[] )
{
	FILE *outfile;
	FILE *infile;
	char FileName[MAXPATH];						// Filename Variable: Used for everything
	char HostName[60]="NOT DEFINED"; 				// LOCAL HOST NAME
	char TimeZone[60]="NOT DEFINED";   				// TIME ZONE
	char FullName[60]="NOT DEFINED";        			// FULL HOST AND LOCAL
	char Organization[60]="NOT DEFINED";    			// ORGANIZATION INFORMATION
	char timeline[30];						// Time for from line
	char time2[30];							// Time for the header
	time_t t;							// Structor for time
	char drive[MAXDRIVE];						// for fnsplit and fnmerge
	char dir[MAXDIR];
	char name[MAXFILE];
	char a[1024]; 							// Array for Reading Lines
	int j,i;
	char ch;

	if (argc != 4)
	{
		// even though Pmail probably won't display this
		fprintf(stderr,"Usage: filter username container-file to-line\n");
		exit(1);
	}

	// if comma is on end of Mail address, trim it off
	while (argv[3][strlen(argv[3])-1]==',')			argv[3][strlen(argv[3])-1]=NULL;

	// drive and directory from Spool file name from input arguments
	fnsplit(argv[2], drive, dir, name, NULL);

	// 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
	// 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

	fnmerge(FileName, drive, dir,"HOST", ".DAT");		// Get Host File name
	// Open File
	if ((infile = fopen(FileName,"r")) == NULL)
	{
		fprintf(stderr,"Open of Host file %s failed\n", FileName);
		exit(1);
	}
	// Read Host Information from File
		while (!feof(infile))
		{
			j=0;							// Initialize Array Pointer to Beginning
			while(((ch=fgetc(infile))!='\n') && !feof(infile))	// 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,"TIME:")!=0)				// Check for TIME: Line
				strcpy(TimeZone,&a[5]);                 	// If Yes, copy Information after TIME:
			if (strstr(a,"ORGAN:")!=0)				// Check for TIME: Line
				strcpy(Organization,&a[6]);                 	// If Yes, copy Information after TIME:
		}
	fclose(infile);							// 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 (TimeZone[strlen(TimeZone)-1]==' ')                       TimeZone[strlen(TimeZone)-1]=NULL;
	while (Organization[strlen(Organization)-1]==' ')               Organization[strlen(Organization)-1]=NULL;

	// Trim Leading blanks from fields
	while (HostName[0]==' ')					strcpy(HostName,&HostName[1]);
	while (FullName[0]==' ')                                        strcpy(FullName,&FullName[1]);
	while (TimeZone[0]==' ')                                        strcpy(TimeZone,&TimeZone[1]);
	while (Organization[0]==' ')                                    strcpy(Organization,&Organization[1]);

	// put 'em together and what do you get?
	fnmerge(FileName, drive, dir, name, ".DAT");
	//
	//	create the data file for mailing
	//
	if ((outfile = fopen(FileName,"wb")) == NULL)
	{
		fprintf(stderr,"Open of DAT file %s failed\n", FileName);
		exit(1);
	}
		if ((infile = fopen(argv[2],"r"))== NULL)
		{
			fprintf(stderr,"Error opening container file %s\n", argv[2]);
			exit(1);
		}
	// Time Line for From Information
			time(&t);
			strcpy(timeline,ctime(&t));
			timeline[24]=NULL;     	// Kill newline from string

			for(i=0;i<3;i++)			// Rather than have Pmail
				time2[i]=timeline[i];           // Create the Time in the
			time2[3]=',';                           // Same Format.
			time2[4]=' ';                           // Weekday, day Mnth Year Time
			time2[5]=timeline[8];                   // Fri,  1 Apr 1994 21:05:36
			time2[6]=timeline[9];                   // This reduces the Information
			time2[7]=' ';                           // passed from PMAIL. Long addresses
			time2[8]=timeline[4];                   // could cause failures.
			time2[9]=timeline[5];
			time2[10]=timeline[6];
			time2[11]=' ';
			for(i=12;i<16;i++)
				time2[i]=timeline[i+8];
			time2[16]=' ';
			for(i=11;i<19;i++)
				time2[i+6]=timeline[i];
			time2[25]=NULL;

//	fprintf(outfile,"From %s!%s %s remote from %s\n", FullName, argv[1], timeline, HostName);
//      Test Change for Keuntos problem
			fprintf(outfile,"From %s  %s %s remote from %s\n", argv[1], timeline, TimeZone, FullName);
			fprintf(outfile,"Received: by %s (PMAIL Filter)\n", FullName);
			fprintf(outfile,"\tvia UUCP; %s %s\n", time2, TimeZone);
			fprintf(outfile,"\tfor <%s>\n",argv[3]);
			fprintf(outfile,"Message-ID: <%s@%s>\n", name, FullName);

			while (!feof(infile))
			{
				j=0;							// Initialize Array Pointer to Beginning
				while(((ch=fgetc(infile))!='\n') && !feof(infile))	// 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[0]=='T' && a[1]=='o' && a[2]==':' && a[3]==' ')	// Trim extra spaces
				{                                                       // After To:
					strcpy(&a[4],&a[15]);                           // Waffle Problem, Not PMAIL
				}                                                       // But this fixes it.

				if (a[0]=='F' && a[1]=='r' && a[2]=='o' && a[3]=='m' && a[4]==':' && a[5]==' ')	   	// Trim extra spaces
				{                                                       		       		// After From:
					strcpy(&a[6],&a[15]);                           				// Waffle Problem, Not PMAIL
				}                                                       				// But this fixes it.

				if (a[0]=='S' && a[1]=='u' && a[2]=='b' && a[3]=='j' && a[4]=='e' && a[5]=='c'&& a[6]=='t' && a[7]==':')
					fprintf(outfile,"Organization:  %s\n",Organization);
				fprintf(outfile,"%s\n",a);
			}
		fclose(infile);
	fclose(outfile);


// create the ".CMD" file - commands to UUCICO (?)
// 	Format:
// 	S 0051.DAT D.home0051 brendan - 0051.DAT 0666
// 	S 0051.XQT X.home0051 brendan - 0051.XQT 0666
//
// 	(roughly)
//  	SEND local-filename as-filename from - ????? unix-file-mode
//
	fnmerge(FileName, drive, dir, name, ".CMD");
	if ((outfile = fopen (FileName,"w")) == NULL)
	{
		fprintf(stderr,"Open of CMD file %s failed\n", FileName);
		exit(1);
	}

		fnmerge(FileName, NULL, NULL, name, NULL);

		fprintf(outfile, "S %s.DAT D.%s%s %s - %s.DAT 0666\n", FileName, HostName, name, argv[1], FileName);
		fprintf(outfile, "S %s.XQT X.%s%s %s - %s.XQT 0666\n", FileName, HostName, name, argv[1], FileName);
	fclose(outfile);

//  	Create the ".XQT" file --  commands to uuxqt at the other end!
//
//
//  	Format:
//  	U brendan home
//  	Z
//  	F D.home0051
//  	I D.home0051
//  	C rmail brendan
//
//  	where the commands defined in the uuxqt file are (as stated by
//      Ian Taylor (Ian@airs.com, uunet!airs!ian) in a newsitem posted
//  	to comp.unix.internals 4 Apr 1992)
//
//  	"Here are the commands defined in uuxqt files:
//
//  	 C command-line
//  	 I standard-input
//  	 O standard-output [ system ]
//  	 F required-file filename-to-use
//  	 R requestor-address
//  	 U user system
//  	 Z (acknowledge if command failed; default)
//  	 N (no acknowledgement on failure)
//  	 n (acknowledge if command succeeded)
//  	 B (return command input on error)
//  	 e (process with sh)
//  	 E (process with exec)
//  	 M status-file
//  	 # comment
//
//
	fnmerge(FileName,drive, dir, name, ".XQT");
	if ((outfile = fopen (FileName,"w")) == NULL)
	{
		fprintf(stderr,"Open of XQT file %s.XQT failed\n", FileName);
		exit(1);
	}
		fprintf(outfile,"U %s %s\n", argv[1], FullName);
		fprintf(outfile,"Z\n");
		fprintf(outfile,"R %s@%s\n", argv[1], FullName);
		fprintf(outfile,"F D.%s%s\n", HostName, name);
		fprintf(outfile,"I D.%s%s\n", HostName, name);
		fprintf(outfile,"C rmail %s\n", argv[3]);
	fclose(outfile);

// 	Now delete the file created by pmail, 'cos all this worked, didn't it! You might want to stop
//	this from happening, as a log, since uucico deletes the files when finished, or just in case
//	you're paranoid and might want to re-process it all later.
//	Note: I have chosen to rename the file rather than delete it
//	Later the file is stored in a Zip file
	fnmerge(FileName, drive, dir, name, ".WWM"); 		/* RENAME FILE */
	if ( (rename(argv[2],FileName)) != 0)  			/* Rename Temporary File */
	{
		fprintf(stderr,"Failed to rename PMAIL temporary file %s %s\n", FileName, argv[2]);
		exit(1);
	}
}
