/* EMACS_MODES: !lnumb !fill */
#define NAME "email"
#define VERSION "1.2"

#include <stdio.h>
#include <string.h>
#include <io.h>
#include <fcntl.h>
#include <dos.h>
#include <stdlib.h>
#include <time.h>
#include <dir.h>


#define nl() printf("\n");
#define OK 0
#define ERROR 1
#define FATAL 2

#define EMAIL           0x0002
#define EMAIL_VERBOSE   0x0007

#define STX     '\2'        /* End Of Text */
#define LF	'\012'        /* Form Feed (New Page) */
#define FF	'\014'        /* Form Feed (New Page) */

#define MAXP 256                /* Maximum pN.net ie. p1.net ... pN.net */
#define ERRLOG  "email.err"  /* File to log errors to */

#define MAXSYS  (unsigned short)65535  /* highest node number for WWIVnet */

#define MAXLINE 128         /* Maximum length of a line in a message */
#define MAXELM  30          /* Maximum number of elements for temp. array */
#define MSGLEN  32000       /* Max number of bytes for a single message */

#define CONFIGFLE "fsend.cfg" /* Config file for this program */
#define CONFITEMS 3           /* Number of items in the config file */

FILE *fe;
char array[MAXELM][MAXLINE];   /* temp array */
int error; /* error flag/counter */
int append; /* append to p1.net flag 1=yes, 0=create p1.net-pN.net */
char message[MSGLEN];
short user_p; /* flag is Pfile is specified */

/* From WWIVnet Doc */
typedef struct {
        unsigned short  tosys,         /* destination system */
                        touser,        /* destination user */
                        fromsys,       /* originating system */
                        fromuser;      /* originating user */
        unsigned short  main_type,     /* main message type */
                        minor_type;    /* minor message type */
        unsigned short  list_len;      /* # of entries in system list */
        unsigned long   daten;         /* date/time sent */
        unsigned long   length;        /* # of bytes of msg after header */
        unsigned short  method;        /* method of compression */
} net_header_rec;

net_header_rec nh;

void main(int argc, char *argv[])
{
	int i,j,p;
	long T;
	char s[MAXLINE];

	
	error=0;
	colour(4);
	printf("[%s:%s] Copyright (c) 1991 Andrew Gaunt. ",NAME,VERSION);
	colour(0);
	nl();
	colour(3);
	printf("Compile date and time %s %s",__DATE__,__TIME__);
	colour(0);
	nl();

	if (argc<10){
		printf("usage: file title touser tonode from_usernum from_username\\\n       fromnode major minor data_dir [n]\n",argv[0]);
		printf("\nfile=pathname for file to emailed, \"-\" for stdin");
		printf("\ntitle=title of message (single argument)");
		printf("\ntouser=destination user's number");
		printf("\ntonode=destination node");
		printf("\nfrom_usernum=originating user's number");
		printf("\nfrom_username=originating user's name");
		printf("\nfromnode=originating node");
		printf("\nmajor=number, \"email\", \"prepost\", \"verbose\"");
		printf("\nminor=number");
		printf("\ndata_dir=wwiv bbs's data directory");
		printf("\n[n]=create or append to p[n].net (optional)");
		printf("\n");
		printf("\ne.g. email file.txt TITLE_OF_MESSAGE 1 6301 1 QUANTUM 6300 email 0 /wwiv/data");
		printf("\n");
		exit(0);
	}

	/* Open the error log file */	if ( (fe=fopen(ERRLOG,"w")) == NULL ){
		colour(6);
		printf("FATAL: can't open error log %s for writing.",ERRLOG);
		colour(0);
		nl();
		myexit(FATAL);
	}

/* 	putchar(FF); */
	colour(0);
	/* Allow user to specify p?.net file, >= p0.net */
	user_p=0;
	p=0;
	if (argc==12){
		user_p=1;
		p=atoi(argv[11]);
		if(p<0){
			p=0;
		}
	}		
	if(create_netfile(argv[1],argv[2],argv[3],argv[4],argv[5],argv[6],argv[7],argv[8],argv[9],argv[10],p) != OK){
		myexit(FATAL);
	}
        nl();
        colour(4);
	printf("[%s:%s] Complete ",NAME,VERSION);
	colour(0);
	nl();
        exit(0);
}

create_netfile(filepath,title,touser,tonode,fromunum,fromuname,fromnode,major,minor,data,p)
char filepath[];
char title[];
char touser[];	
char tonode[];
char fromunum[];
char fromuname[];
char fromnode[];
char major[];
char minor[];
char data[];
int p;
{
	FILE *fi,*fo;
	struct date datep;
	struct time timep;
	unsigned long num_read;
	char outfile[MAXPATH];
	char s[MAXLINE];
	char post_date[30];
	long T;
	int i;
	int msgnum;

	/* Create next for output p?.net */

	i = p;
	if (user_p==1){
		sprintf(outfile,"%s/P%d.NET",data,p);
		fo = fopen(outfile, "ab");
		if (fo == NULL){
			sprintf(s,"Can't create %s.\n",outfile);
			errlog(s);
			return(FATAL);
		}
	}
	else{
		do {
			i++;
			sprintf(outfile,"%s/P%d.NET",data,i);
			fo = fopen(outfile, "rb");
			if (fo == NULL) {
				fclose(fo);
				nl();
				fo = fopen(outfile, "ab");
				if (fo == NULL){
					sprintf(s,"Can't create %s.\n",outfile);
					errlog(s);
					return(FATAL);
				}
				break;
			} else {
				fclose(fo);
			}
		} while (i < MAXP);
	}
	colour(3);
	printf("Pfile: %s.\n",outfile);
	colour(0);

	/* Open the input file, specified in the configuration file */
	if (strcmp(filepath,"-")==NULL){
		fi=stdin;
	}
	else{
		if ( (fi=fopen(filepath,"rb")) == NULL ){
			sprintf(s,"Can't read input file %s.\n",filepath);
			errlog(s);
			return(FATAL);
		}
	}
	msgnum=0;
	while( (num_read=read(fileno(fi),(char *)message,MSGLEN))!=0){
/* 		putchar(FF); */
		msgnum++;
		time(&T);
		strcpy(s,ctime(&T));
		/* Don't let post_date contain a newline */
		for(i=0;i<strlen(s);i++){
			if (s[i]==LF){
				post_date[i]='\0';
			}
			else{
				post_date[i]=s[i];
			}
		}	
	
		gettime(&timep);
		getdate(&datep);

		/* Try to convert major types if specified verbosely */
		if (strcmp(major,"email")==NULL){
			strcpy(major,"2");
		}
		if (strcmp(major,"prepost")==NULL){
			strcpy(major,"5");
		}
		if (strcmp(major,"verbose")==NULL){
			strcpy(major,"7");
		}
				
		nh.tosys=(unsigned short)atoi(tonode);
		nh.touser=(unsigned short)atoi(touser);
		nh.fromsys=(unsigned short)atoi(fromnode);
		nh.fromuser=(unsigned short)atoi(fromunum);
		nh.main_type=(unsigned short)atoi(major);
		nh.minor_type=(unsigned short)atoi(minor);
		nh.list_len=0;
		nh.daten=dostounix(&datep, &timep);
		nh.length=num_read+strlen(title)+1+strlen(fromuname)+1+strlen(post_date)+2;
		nh.method=0;
		colour(3);
		print_nh_header();
/* 		printf("Title: %s\n",title); /* DEBUG */
/*		printf(" Name: %s\n",fromuname); /* DEBUG */
/*		printf(" Date: %s\n",post_date); /* DEBUG */
		colour(0);
		nl();
		fflush(fo);
	 	write(fileno(fo),(void *)&nh,sizeof(net_header_rec));
		write(fileno(fo),(void *)title,strlen(title));
		write(fileno(fo),'\0',sizeof(char));
		write(fileno(fo),(void *)fromuname,strlen(fromuname));
		fflush(fo);
		fprintf(fo,"\r");
		fflush(fo);
	 	write(fileno(fo),(void *)post_date,strlen(post_date));
		fflush(fo);
		fprintf(fo,"\r\n");
		fflush(fo);
		colour(2);
		printf("Message #%04d ",msgnum);
		for(i=0;i<num_read;i++){
			fputc(message[i],fo);
		}
		printf(" %d bytes of data.",i);
		colour(0);
		nl();
	}
	fclose(fi);
	fclose(fo);
	return(OK);
}

errlog(s)
char *s[];
{

	fprintf(fe,"ERROR: %s",s);
	error++;
	return(OK);
}

myexit(r)
int r;
{
	char s[MAXLINE];

	/* close the error log */
	fclose(fe);
	if ( (fe=fopen(ERRLOG,"r")) == NULL ){
		printf("FATAL: can't open error log %s for reading.\n",ERRLOG);
		exit(FATAL);
	}
	colour(6);
	printf("%d ERROR(S) have occuured:\n",error);
	colour(1);
	while ( fgets(s,MAXLINE-1,fe)  ){
		printf("\t%s",s);
	}			
	colour(0);
	fclose(fe);
	exit(r);
	return(OK);
}

print_nh_header()
{
	printf("To %u@%u, ",nh.touser,nh.tosys);
	printf("from %u@%u, ",nh.fromuser,nh.fromsys);
	printf("type %u-%u",nh.main_type,nh.minor_type);
/* 	printf("List length : %u\n",nh.list_len); */
/* 	printf("Stamp: %u\n",nh.daten); */
/* 	printf("Total len.  : %u",nh.length); */
/*  	nl();  */
	return(OK);
}

colour(code)
short code;
{
/*
  if (code<=7 && code>=0 ){
    printf("%c%d",'\003',code);
  }
*/
  return(OK);
}

