/*
 * uu2mail.c
 * jskim@bulls.kordic.re.kr
 */

#include "uu2mail.h"
#include <unistd.h>

int GetUniqueFileName(FileName)
	char *FileName;
{
	pid_t		pid;
	struct tm	*timePtr;
	struct tmp	*gettime();
	long		timeval;
	int		i;

	time(&timeval);
	timePtr = gmtime(&timeval);
	pid = getpid();

	sprintf(FileName, "File%d%d", timePtr->tm_yday, pid);

	for (i = 0; i < strlen(FileName); i++)
	{
		if (FileName[i] == ' ')
			FileName[i] = '0';
	}

	return (int) 1;
}

int main()
{
	FILE		*fp;
	char		*srcFile, *srcPath, *email;
	char		srcFileDesc[256];
	char		tmpFile[40];
	getentry	entries[5];

	char		entry_flag = 0;
	char		buf[256];
	char		buf2[256];
	char		*ptr;
	register	int	i, x;

	printf("content-type: text/html\n\n");	/* HTML Header */
	printf("<html>\n");
	printf("<head>\n");
	printf("<title>uu2mail RESULT</title>\n");
	printf("</head>\n");
	printf("<body bgcolor=\"black\"><center>\n");
	printf("<iframe width=480 height=70 frameborder=0 marginheight=0 scrolling=no ");
	printf("marginwidth=0 bgcolor=black src=/animal/AD/ad.cgi?bgcolor=black></iframe>");

#ifdef FILEOUT
printf("Debugging Mode\n");
	i = 2;
	strcpy(entries[0].name, "email");
	strcpy(entries[0].val, "jskim@bulls.kordic.re.kr");
	strcpy(entries[1].name, "srcFile");
	strcpy(entries[1].val, "animal4/KoreanInsect-GrasslandLong-hornedBeetle.jpg");
#else
	i = ProcessGetMethod( entries );
#endif

	GetUniqueFileName(tmpFile);

	for (x = 0; x <= i; x++)
	{
		if (!strcmp(entries[x].name, "email"))
		{
			email = (char *) malloc(strlen(entries[x].val)+1);
			strcpy(email, entries[x].val);
			if (strlen(email)>2)
				entry_flag++;
			continue;
		}
		if (!strcmp(entries[x].name, "srcFile"))
		{
			strcpy(buf, entries[x].val);
		    if (strstr(buf, "Jose_Sierra_Jr")) {
			printf("<p><font color=yellow face=\"Comic Sans MS\" size=+1>\n");
			printf("Sorry. This image is not allowed to download.<br>\n");
			printf("</font>\n");
			exit(0);
		    }
			while (ptr = (char *)strstr(buf, "/"))
			{
				strcpy(buf, ptr+1);
			}
			srcFile = (char *) malloc(strlen(buf)+1);
			strcpy(srcFile, buf);
			strcpy(buf, entries[x].val);
			ptr = (char *) strstr(buf, srcFile);
			*ptr = '\0';
			srcPath = (char *) malloc(strlen(buf)+1);
			strcpy(srcPath, buf);
			if (strlen(srcFile)>2)
				entry_flag++;
			continue;
		}
	}

	if (entry_flag !=2)
	{
	    /* make preview file name */
	    strcpy(buf, srcFile);
	    for (i=strlen(buf); i > 0; i--) {
		if (buf[i] == '.') {
		    if (!strcasecmp(buf+i, ".jpg"))
			strcpy(buf+i, "-s160.jpg");
		    else if (!strcasecmp(buf+i, ".gif"))
			strcpy(buf+i, "-s160.gif");
		    break;
		}
	    }

	    printf("<center>\n");
	    printf("<font size=+2 color=black>Mail: %s</font>\n", srcFile);
	    printf("<table border=1 width=60%c bgcolor=#BBBBBB>\n", '%');
	    printf("<tr><th width=164><img border=2 src=PREVIEW/%s></td>\n", buf);
	    printf("<th>\n");
	    printf("<font size=+2>uu2mail</font><br>\n");
	    printf("Mail a binary file in uuencoded form\n");
	    
	    printf("<center>\n");
	    printf("<tr><th colspan=2>\n");
	    printf("\n<form action=\"uu2mail.cgi\" method=\"GET\">\n");

	    printf("<p>Send The <font size=2 color=\"blue\">");
	    printf("<b>Image</b></font><br>\n");
	    printf("\"<u>%s%s</u>\"</i><p>\n", srcPath, srcFile);
	    printf("To\n");
	    printf("<br>Your <font size=2 color=\"blue\">");
	    printf("<b>E-mail Address.</b></font><br>\n");
	    printf("<input name=\"email\" type=\"text\" size=40 ");
	    printf("value=\"%s\"><p>", email);
	    
	    printf("<tr><th colspan=2>\n");
	    printf("<input name=\"srcFile\" type=hidden ");
	    printf("value=\"%s%s\"><p>", srcPath, srcFile);
	    
	    printf("<input type=\"submit\" name=\"submit\" ");
	    printf("value=\"SEND\">");
	    printf("<input type=\"reset\" name=\"reset\" ");
	    printf("value=\"CLEAR\">");
	    printf("</form>\n\n");

	    printf("<tr><th colspan=2>\n");
	    printf("<font size=+1>\n");
	    printf("<a href=\"%s\">Animal Pictures Archive</a><p>\n", URL_HOME);
	    printf("</font>\n</center>\n</body>\n");
	    printf("</td></tr></table>\n");
	    printf("</html>\n");

	    exit(0);
	}

/*
	srcFileDesc = (char *) malloc(strlen(srcFile)+2);
*/
	strcpy(buf, srcFile);
	for (i = strlen(srcFile); i > 0; i--)
	{
		if (buf[i] == '.')
		{
			buf[i] = '\0';
			break;
		}
	}

	while (1)
	{
		strcpy(srcFileDesc, srcPath);
		strcat(srcFileDesc, buf);
		strcat(srcFileDesc, ".txt");
		if ( (fp=fopen(srcFileDesc, "r")) == NULL ) ;
		else
		{
			sprintf(buf2, "%s %s > %s/%s", CAT_COMMAND,\
				srcFileDesc, TEMP_DIR, tmpFile);
			system(buf2);
			fclose(fp);
			break;
		}

		strcpy(srcFileDesc, srcPath);
		strcat(srcFileDesc, buf);
		strcat(srcFileDesc, ".TXT");
		if ( (fp=fopen(srcFileDesc, "r")) == NULL ) ;
		else
		{
			sprintf(buf2, "%s %s >> %s/%s", CAT_COMMAND,\
				srcFileDesc, TEMP_DIR, tmpFile);
			system(buf2);
			fclose(fp);
			break;
		}

		strcpy(srcFileDesc, srcPath);
		strcat(srcFileDesc, buf);
		strcat(srcFileDesc, ".html");
		if ( (fp=fopen(srcFileDesc, "r")) == NULL ) ;
		else
		{
			sprintf(buf2, "%s %s >> %s/%s", CAT_COMMAND,\
				srcFileDesc, TEMP_DIR, tmpFile);
			system(buf2);
			fclose(fp);
			break;
		}
		break;
	}

	sprintf(buf2, "%s/%s", TEMP_DIR, tmpFile);
	fp = fopen(buf2, "a");
	fprintf(fp, "\n\nuuencoded and mailed by ");
	fprintf(fp, " [Animal Pictures Archive(http://www.best5.net/animal/)]\n");
	fprintf(fp, "    Contact jskim@www.best5.net for any comments.\n");
	fprintf(fp, "************ %s ************\n", URL_HOME);
	fprintf(fp, "\n---- Cut Here ---- Cut Here ---- ");
	fprintf(fp, "Cut Here ---- Cut Here ----\n\n");
	fclose(fp);

	sprintf(buf, "%s%s", srcPath, srcFile);
	if ( (fp=fopen(buf, "r")) == NULL )
	{
		printf("<font size=+1>Can't open file <b><tt>%s</tt></b>\n",\
					buf);
		printf("<br>Back and try again.<br>\n</font>\n");
		printf("<hr>\n<center>\n<font size=+1>\n");
		printf("<p><a href=\"%s\">Go Back To Home</a><p>\n", URL_HOME);
		printf("</font>\n</center>\n</body>\n");
		printf("</html>\n");
		exit(1);
	}

	sprintf(buf, "%s %s%s %s >> %s/%s", UUENCODE, srcPath, srcFile, \
					srcFile, TEMP_DIR, tmpFile);
	if (system(buf) == -1)
	{
		printf("<hr>");
		printf("<center>\nThere is a problem during uuencode.<br>\n");
		printf("Back and try again.<br>\n</center>\n");
		printf("<hr>\n<center>\n<font size=+1>\n");
		printf("<p><a href=\"%s\">Go Back To Home</a><p>\n", URL_HOME);
		printf("</font>\n</center>\n</body>\n");
		printf("</html>\n");
		exit(1);
	}

	/* for mail */
	sprintf(buf, "%s -s \"%s\" \"%s\" < %s/%s", MAIL_COMMAND, srcFile, email, TEMP_DIR, tmpFile);

/* for elm
	sprintf(buf, "%s -s %s %s < %s/%s", MAIL_COMMAND, srcFile, email, TEMP_DIR, tmpFile);
*/
	if (system(buf) == -1)
	{
		printf("<hr>\n<center>\n");
		printf("There is a problem during mail.<br>\n");
		printf("Back and try again.<br>\n</center>\n");
		printf("<hr>\n<center>\n<font size=+1>\n");
		printf("<p><a href=\"%s\">Go Back To Home</a><p>\n", URL_HOME);
		printf("</font>\n</center>\n</body>\n");
		printf("</html>\n");
		exit(1);
	}

	printf("<center><table bgcolor=#BBBBBB width=60%c><tr><th>\n", '%');
	printf("<center><font color=\"blue\"><tt>%s%s</tt></font><br>\
		will be ", srcPath, srcFile);
	printf("mailed to <font color=\"blue\">%s</font> in uuencoded \
		form.<br>\n", email);
	printf("Save the mail as a text file and <font color=\"red\"> \
		<tt>uudecode</tt></font> it.<br>\n");
	printf("<p>Good Luck !!!<p>\n");

	printf("<hr>\n<font size=+1>\n");
	printf("<p><a href=\"%s\">Go Back To Home</a><p>\n", URL_HOME);
	printf("</font>\n</center>\n</body>\n");
	printf("</table>\n");
	printf("</html>\n");

	sprintf(buf, "%s/%s", TEMP_DIR, tmpFile);
	unlink(buf);

	free(email); free(srcFile); free(srcPath);
/*
	free(srcFileDesc);
*/
	exit(0);
}

/* NCSA Web Library */
void 
getword(char *word, char *line, char stop)
{
	int             x = 0, y;

	for (x = 0; ((line[x]) && (line[x] != stop)); x++)
		word[x] = line[x];

	word[x] = '\0';
	if (line[x])
		++x;
	y = 0;

	while (line[y++] = line[x++]);
}

char           *
makeword(char *line, char stop)
{
	int             x = 0, y;
	char           *word = (char *) malloc(sizeof(char) * (strlen(line) + 1));

	for (x = 0; ((line[x]) && (line[x] != stop)); x++)
		word[x] = line[x];

	word[x] = '\0';
	if (line[x])
		++x;
	y = 0;

	while (line[y++] = line[x++]);
	return word;
}

char           *
fmakeword(FILE * f, char stop, int *cl)
{
	int             wsize;
	char           *word;
	int             ll;

	wsize = 102400;
	ll = 0;
	word = (char *) malloc(sizeof(char) * (wsize + 1));

	while (1)
	{
		word[ll] = (char) fgetc(f);
		if (ll == wsize)
		{
			word[ll + 1] = '\0';
			wsize += 102400;
			word = (char *) realloc(word, sizeof(char) * (wsize + 1));
		}
		--(*cl);
		if ((word[ll] == stop) || (feof(f)) || (!(*cl)))
		{
			if (word[ll] != stop)
				ll++;
			word[ll] = '\0';
			return word;
		}
		++ll;
	}
}

char 
x2c(char *what)
{
	register char   digit;

	digit = (what[0] >= 'A' ? ((what[0] & 0xdf) - 'A') + 10 : (what[0] - '0'));
	digit *= 16;
	digit += (what[1] >= 'A' ? ((what[1] & 0xdf) - 'A') + 10 : (what[1] - '0'));
	return (digit);
}

void 
unescape_url(char *url)
{
	register int    x, y;

	for (x = 0, y = 0; url[y]; ++x, ++y)
	{
		if ((url[x] = url[y]) == '%')
		{
			url[x] = x2c(&url[y + 1]);
			y += 2;
		}
	}
	url[x] = '\0';
}

void 
plustospace(char *str)
{
	register int    x;

	for (x = 0; str[x]; x++)
		if (str[x] == '+')
			str[x] = ' ';
}

int 
rind(char *s, char c)
{
	register int    x;
	for (x = strlen(s) - 1; x != -1; x--)
		if (s[x] == c)
			return x;
	return -1;
}

int 
getline(char *s, int n, FILE * f)
{
	register int    i = 0;

	while (1)
	{
		s[i] = (char) fgetc(f);

		if (s[i] == CR)
			s[i] = fgetc(f);

		if ((s[i] == 0x4) || (s[i] == LF) || (i == (n - 1)))
		{
			s[i] = '\0';
			return (feof(f) ? 1 : 0);
		}
		++i;
	}
}

void 
send_fd(FILE * f, FILE * fd)
{
	int             num_chars = 0;
	char            c;

	while (1)
	{
		c = fgetc(f);
		if (feof(f))
			return;
		fputc(c, fd);
	}
}

/* coded by armian@www.kordic.re.kr */
int
ProcessGetMethod(entries)
getentry	*entries;
{
	char	*cl;
	int	x, m;

	if (strcmp(getenv("REQUEST_METHOD"), "GET"))
        {
                printf("This script should be referenced with a METHOD of GET.\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);
        }

        cl = getenv("QUERY_STRING");
        if (cl == NULL)
        {
                printf("No query information to decode.\n");
                exit(1);
        }

        for (x = 0; cl[0] != '\0'; x++)
        {
                m = x;
                getword(entries[x].val, cl, '&');
                plustospace(entries[x].val);
                unescape_url(entries[x].val);
                getword(entries[x].name, entries[x].val, '=');
        }

	return m;
}
