/*
 * Adapted from imagemap.c and post-query.c as distributed by NCSA.
 *
 * Changes Copyright Mike W. Meyer, 1994 
 */

#include <stdio.h>
#include <string.h>
#ifndef pyr
#include <stdlib.h>
#else
#include <ctype.h>
#endif

#include <sys/types.h>
#include <pwd.h>
#define CONF_FILE "mailmap.conf"
#ifndef	AMIGA
#define CONF_DIRECTORY "/usr/local/etc/http/conf"

#else	/* AMIGA */
#define CONF_DIRECTORY	"aws:conf"

/* Some prototypes... */
#include <ctype.h>
#include <proto/usergroup.h>
void servererr(char *);
int getline(char *s, int n, FILE *f);
FILE *runmail(void) ;
void endmail(void) ;
void unescape_url(char *) ;
void plustospace(char *) ;
char *fmakeword(FILE *, char, int *) ;

#endif

#define MAXLINE 500
#define isname(c) ((c) && !isspace(c))

int main(int argc, char **argv)
{
    char buffer[MAXLINE], *mapname, *dir, *t ,
    	 *url, *address, *subject, *name, *value;
    int i, length;
    FILE *fp;
    struct passwd *pwd;
    
    mapname=getenv("PATH_INFO");
    if((!mapname) || (!mapname[0]))
        servererr("No map name given. Please read the <A HREF=\"http://www.mired.org/user-docs/mailmap.html\">instructions</A>.<P>");
    mapname++;

    /* Look for a user name at the start of the map name */
    dir = CONF_DIRECTORY;
    if ((t = strchr(mapname, '/')) != NULL) {
	*t = '\0';
        if ((pwd = getpwnam(mapname)) == NULL)
	    *t = '/';
	else {
	    dir = pwd->pw_dir;
	    mapname = t + 1;
	    }
	}

/* MWM - change this so the Amiga version uses AddPart */
    sprintf(buffer, "%s/%s", dir, CONF_FILE) ;

    if ((fp = fopen(buffer, "r")) == NULL)
        servererr("Couldn't open configuration file.");

    while(!(getline(buffer,MAXLINE,fp))) {
        if((buffer[0] == '#') || (!buffer[0]))
            continue;
        for(i=0;isname(buffer[i]) && (buffer[i] != ':');i++)
		;
        buffer[i] = '\0';
        if(!strcmp(buffer,mapname))
            goto found;
    }
    if(feof(fp))
        servererr("Map not found in configuration file.");
  found:
    fclose(fp);
    if (++i >= MAXLINE) servererr("Invalid line found in configuration file");
    while(isspace(buffer[i]) || buffer[i] == ':') ++i;

    /* Parse the line we found */
    url = &buffer[i];
    while (isname(buffer[i])) i += 1;
    if (i >= MAXLINE) servererr("Invalid line found in configuration file");
    buffer[i] = '\0' ;
    i += 1;
    while (isspace(buffer[i])) i += 1;
    if (i >= MAXLINE) servererr("Invalid line found in configuration file");

    address = &buffer[i];
    while (isname(buffer[i])) i += 1;
    if (i >= MAXLINE) servererr("Invalid line found in configuration file");
    buffer[i] = '\0' ;
    i += 1;
    while (isspace(buffer[i])) i += 1;
    if (i >= MAXLINE) servererr("Invalid line found in configuration file");
    subject = &buffer[i] ;

    /* make sure we've got a type we understand */
    if(strcmp(getenv("REQUEST_METHOD"),"POST")) {
        printf("This script should be referenced with a METHOD of POST.\n");
        printf("If you don't understand this, see this ");
        printf("<A HREF=\"http://www.ncsa.uiuc.edu/SDG/Software/Mosaic/Docs/fill-out-forms/overview.html\">forms overview</A>.%c",10);
        exit(1);
    }

    if(strcmp(getenv("CONTENT_TYPE"),"application/x-www-form-urlencoded"))
        servererr("This script can only be used to decode form results.");

    /* Ok, Got everything we need so far, start feeding the mail process */
    fp = runmail() ;

    fprintf(fp, "To: %s\nSubject: %s\n", address, subject) ;
   length = atoi(getenv("CONTENT_LENGTH")) ;

    /* Handle the first one specially */
    if (!length || feof(stdin)) putc('\n', fp) ;
    else {
	   name = fmakeword(stdin, '&', &length) ;
	   plustospace(name) ;
	   value = strchr(name, '=') ;
	   if (!value) fprintf(fp, "\n:0 %s\n%s\n", name) ;
	   else {
		   unescape_url(value) ;
		   for (i = 1, t = value; t = strchr(t + 1, '\n'); i += 1)
			   ;
		   *value++ = '\0' ;
		   if (!stricmp(name, "replyto") && *value)
			   fprintf(fp, "Reply-To: %s\n", value) ;
		   fprintf(fp, "\n:%d %s\n%s\n", i, name, value) ;
	   }
    }
	   
    while (length && !feof(stdin)) {
	   name = fmakeword(stdin, '&', &length) ;
	   plustospace(name) ;
	   value = strchr(name, '=') ;
	   if (!value) fprintf(fp, "\n:0 %s\n%s\n", name) ;
	   else {
		   unescape_url(value) ;
		   for (i = 1, t = value; t = strchr(t + 1, '\n'); i += 1)
			   ;
		   *value++ = '\0' ;
		   fprintf(fp, "\n:%d %s\n%s\n", i, name, value) ;
	   }
    }
    endmail() ;	    

    /* Finally, send the the client where the user wants it sent */
    printf("Location: %s%c%c",url,10,10);
    printf("This document has moved <A HREF=\"%s\">here</A>%c",url,10);
}

void
servererr(char *msg)
{
    printf("Content-type: text/html%c%c",10,10);
    printf("<title>Mapping Server Error</title>");
    printf("<h1>Mapping Server Error</h1>");
    printf("This server encountered an error:<p>");
    printf("%s", msg);
    exit(-1);
}


#if defined(DEBUG)
FILE *
runmail(void) {

	printf("Content-Type: text/plain%c%c", 10, 10) ;
	return stdout ;
	}

void
endmail(void) { }


#elif defined(AMIGA)
#include <proto/exec.h>

static FILE *amiga_pipe ;
FILE *
runmail(void) {
	char command[MAXLINE], pipe_name[30] ;

	sprintf( pipe_name, "pipe:mailmap-%d", FindTask( NULL ) );
	sprintf(command,
		"run %s -f admin -R \"WWW Forms Mail Interface\" <%s\n",
		getenv("SENDMAIL"), pipe_name) ;
	amiga_pipe = fopen(pipe_name, "w") ;
	if (amiga_pipe) system(command) ;
	else servererr("Could not open pipe.") ;

	return amiga_pipe ;
	}

void
endmail(void) {
	fclose(amiga_pipe) ;
	}
#elif 1

static FILE *pipe ;

runmail(void) {
	pipe = popen("/usr/lib/sendmail -t \"-FWWW Forms Mail Interface\"",
		     "w") ;
	if (!pipe) servererr("Could not open pipe") ;
	return pipe ;
	}

void
endmail(void) {
	pclose(pipe) ;
	}
#endif
