/*
 *
 *  AM --- AmigaMail
 *  (C) 1991, 1992 by Christian Riede
 *
 *  AM is distributed in the hope that it will be useful, but WITHOUT ANY
 *  WARRANTY.  No author or distributor accepts responsibility to anyone
 *  for the consequences of using it or for whether it serves any
 *  particular purpose or works at all, unless he says so in writing.
 *  Refer to the GNU General Public License, Version 1, for full details.
 *  
 *  Everyone is granted permission to copy, modify and redistribute AM,
 *  but only under the conditions described in the GNU General Public
 *  License, Version 1.  A copy of this license is supposed to have been 
 *  given to you along with AM so you can know your rights and responsi-
 *  bilities.  It should be in a file named COPYING.  Among other things,
 *  the copyright notice and this notice must be preserved on all copies.
 *
 *  
 *
 */

#include "am.h"

static void DisplayMail(char *Mailname)
{
	ULONG err;
	char DisplayCommand[200];
	char MsgId[20];
	char Scriptname[20];
	FILE *script;

	/* build script */
	sprintf(Scriptname,"t:%s",NewMsgId(MsgId));
	if (!(script = fopen(Scriptname,"w")))
		return;
	fprintf(script,"more %s\n",Mailname);
#if 0
	fprintf(script,"echo \"------------- end of mail -------------\"\nask \"press enter\"\nendcli\n");
#else
	fprintf(script,"endcli\n");
#endif
	fclose(script);

	/* command to execute script */
	sprintf(DisplayCommand,"c:newshell \"Con:%d/%d/%d/%d/Displaying Mail/SCREEN %s\" %s",
		WLeft,WTop,WWidth,WHeight,PUBSCREENNAME,Scriptname);

	/* start display process */	
	if (err = SystemTags((UBYTE *)DisplayCommand,
		NP_StackSize,50000,
		TAG_END,0))
	{
		/* abusing DisplayCommand as text buffer */
		Fault(err,(UBYTE *)"Error:\n",(UBYTE *)DisplayCommand,200);
		SimpleRequest(Window,DisplayCommand);
	}

	/* delete script */
	DeleteFile((UBYTE *)Scriptname);
}


void CallMetamail(char *Mailname,char *Action)
{
	ULONG err;
	char DisplayCommand[200];
	char MsgId[20];
	char Scriptname[20];
	FILE *script;

	/* build script */
	sprintf(Scriptname,"t:%s",NewMsgId(MsgId));
	if (!(script = fopen(Scriptname,"w")))
		return;
	if (Action)
		fprintf(script,"%s -r -x -d -a %s %s\n",METAMAIL,Action,Mailname);
	else
		fprintf(script,"%s %s\n",METAMAIL,Mailname);
	fprintf(script,"echo \"------------- end of mail -------------\"\nask \"press enter\"\nendcli\n");
	fclose(script);

	/* command to execute script */
	sprintf(DisplayCommand,"c:newshell \"Con:%d/%d/%d/%d/Displaying Mail/SCREEN %s\" %s",
		WLeft,WTop,WWidth,WHeight,PUBSCREENNAME,Scriptname);

	/* start display process */	
	if (err = SystemTags((UBYTE *)DisplayCommand,
		NP_StackSize,50000,
		TAG_END,0))
	{
		/* abusing DisplayCommand as text buffer */
		Fault(err,(UBYTE *)"Error:\n",(UBYTE *)DisplayCommand,200);
		SimpleRequest(Window,DisplayCommand);
	}

	/* delete script */
	DeleteFile((UBYTE *)Scriptname);
}

int notplain(char *s)
{
    char *t;
    if (!s) return(1);
    while (*s && isspace(*s)) ++s;
    for(t=s; *t; ++t) if (isupper(*t)) *t = tolower(*t);
    while (t > s && isspace(*--t)) {;}
    if (((t-s) == 3) && !strncmp(s, "text", 4)) return(0);
    if (strncmp(s, "text/plain", 10)) return(1);
    t = (char *) index(s, ';');
    while (t) {
        ++t;
        while (*t && isspace(*t)) ++t;
        if (!strncmp(t, "charset", 7)) {
            s = (char *) index(t, '=');
            if (s) {
                ++s;
                while (*s && isspace(*s)) ++s;
                if (!strncmp(s, "us-ascii", 8)) return(0);
                if (!strncmp(s, "iso-8859-1", 8)) return(0);
            }
            return(1);
        }
        t = (char *) index(t, ';');
    }
    return(0); /* no charset, was text/plain */
}


static int TheReadMail(int argc,char **argv,char **environ)
{
	FILE *fp;
	char line[1000], *s, *t;
	int done=FALSE;

	/* check if necessary to call metamail */
    if (fp=fopen(argv[1], "r")) /* argv[1] is the name of the file containing the mail */
	{
		while (fgets(line, sizeof(line), fp)) 
		{
			/* end of header? */
		    if (line[0] == '\n') break; 

			/* to lower */
		    for (s=line; *s; ++s) if (isupper(*s)) *s = tolower(*s);

			/* content-type? */
		    if (!strncmp(line, "content-type:", 13)) 
			{
				s = &line[13];
				while (*s && isspace(*s)) ++s;
				t = index(s, ';');
				if (t) 
				{
				    *t = (char) NULL;
				} 
				else 
				{
				    t = index(s, '\n');
				    if (t) *t = (char) NULL;
				}
				if (t--) 
				    while (isspace(*t) && (t > s)) 
						*t-- = (char) NULL;
				if (notplain(s)) 
				{
					CallMetamail(argv[1],0);
					done=TRUE;
				}
		    }
		    if (!strncmp(line, "content-transfer-encoding:", 26))
			{
				s = &line[26];
				while (*s && isspace(*s)) ++s;

				if (strncmp(s,"8bit",4) && 
					strncmp(s,"7bit",4) && 
					strncmp(s,"binary",6)) /* mail is encoded */
		
				{
					CallMetamail(argv[1],0);
					done=TRUE;
				}
			}
 
		}
		fclose(fp);
	}

	if (!done)
		DisplayMail(argv[1]);

	return(0);
}



/* interface stub fo TheReadMail() */
void ReadMail(void)
{
	register char *arg __asm__ ("a0");
	char *thearg;
	char *argv[2];
	void *ixb;

	/* This causes a warning with gcc: 'arg' may be used unitialized. Don't worry */
	thearg = arg; /* a0 is scratch register */

	running++;

	if (!(ixb  = OpenLibrary ((UBYTE *)"ixemul.library", IX_VERSION)))
	{
		SimpleRequest(Window,"Can't open ixemul.library!");
		return;
	}

	argv[0] = "AM_ReadMail";
	argv[1] = thearg;

	ix_exec_entry(2,argv,0,0,TheReadMail);

	CloseLibrary(ixb);

	Forbid();

	running--;
}
