#include "main.h"
#include <sys/fcntl.h>
#include <stdlib.h>
#include <stdio.h>

extern char* yytext;
extern FILE* yyin;

void auth(login, pwd)
char*login;
char*pwd;
{
	printf("002 Hello, %s. You supplied '%s' as pwd!\n", login, pwd);
	fprintf(stderr, "002 Hello, %s. You supplied '%s' as pwd!\n", login, pwd);
	fflush(stdout);
}
void getmsg(msgid)
char*msgid;
{
	int file;
	int bytesread;
	char* buf;
	char filename[1024];
	char* MAILDIR = "./mail";	// TODO get from environment

	snprintf(filename, 1024, "%s/%s", MAILDIR, msgid);
	file = open(filename, O_RDONLY | O_EXLOCK);
	if (file == -1) {
		printf("010 User '%s' has no messages!\n", msgid);
		fflush(stdout);
	} else {
		buf = (char*) malloc(1024);
		if (buf == NULL) {
			printf("I will not follow a NULL pointer, as the system won't let me access the interrupt table\n");
			exit(-1);
		}
		while((bytesread = read(file, buf, 1024)) > 0) {
			fwrite(buf, bytesread, 1, stdout);
		}
		close(file);
		fflush(stdout);
		free(buf);
	}
}

void yyerror(msg)
char*msg;
{
	printf("023 WTF: %s [%s] \n", msg, yytext);
}

main()
{
	fprintf(stderr, "accepted connection");
	printf("220-1 mail retrieval server\n");
	printf("220-1 (C) 2007, COMES WITH ABSOLUTELY NO WARRANTY\n");
	printf("220 ready\n");
	fflush(stdout);
	char buf[1024];
	int rl = 1;
	char*tmp=buf;
	while (rl) {
		rl = fread(tmp++,1,1,stdin);
		if (memcmp(tmp-5,"quit\n",5) == 0) {
			break;
		}
	}
	char* tmpfn=strdup("/var/tmp/retserver.XX");
	int tmpfile = mkstemp(tmpfn);
	if (tmpfile == -1) {
		printf("shit!\n");
		exit(-1);
	}
	printf("%d\n", rl);
	FILE* mystream = fdopen(tmpfile, "w");
	fwrite(buf, 1, tmp-buf, mystream);
	fflush(mystream);
	lseek(tmpfile, 0, SEEK_SET);
	yyin = fdopen(tmpfile, "r");
	yyparse();
}
