#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <errno.h>

#include "module.h"
#include "hostinfo.h"
#include "weblib.h"

static char     hostname[128];
char     username[256];

#define MBSIZE	1024

long 
domail(urlB * u)
{
    char           *ptr, *dest, mbuf[MBSIZE];
    time_t          now;
    int             i, e;
    FILE           *sp = Conn->sp;

    if (!hostname[0])
	gethostname(hostname, sizeof(hostname));

    if (!username[0])
    {
	i = respond(R_PROMPT, REQUEST_NAME, (long) &ptr);
	if (i < 1)
	    return -1;
	strcpy(username, ptr);
    }
    if (!strchr(username, '@'))
    {
	strcat(username, "@");
	strcat(username, hostname);
    }
    fp = fopen(Args.Afile, "r");
    if (!fp)
	return errno;

    for (ptr = u->user.txt; *ptr == ' '; ptr++);
    dest = ptr;

    respond(R_STATUS, STATUS_WAITING_RESPONSE, 0);
    if (readline(1, Conn, mbuf, MBSIZE) < 0)
    {
	e = errno;
	LOG(("Fatal error reading first response line\n"));
err_out:
	closeConn(Conn);
	fclose(fp);
	return e;
    }
    if (mbuf[0] != '2')
    {
bad_rsp:LOG(("Unexpected response: %s", mbuf));
	fprintf(sp, "QUIT\n");
	e = EBADREQ;
	goto err_out;
    }
    fprintf(sp, "HELO %s\n", hostname);
    fflush(sp);
    LOG(("Sent HELO %s\n", hostname));
    respond(R_STATUS, STATUS_SENDING_REQUEST, 0);
    if (readline(1, Conn, mbuf, MBSIZE) < 0)
    {
	e = errno;
	goto err_out;
    }
    if (mbuf[0] != '2')
    {
	goto bad_rsp;
    }
    fprintf(sp, "MAIL FROM: <%s>\n", username);
    fflush(sp);
    respond(R_STATUS, STATUS_SENDING_REQUEST, 0);
    if (readline(1, Conn, mbuf, MBSIZE) < 0)
    {
	e = errno;
	goto err_out;
    }
    if (mbuf[0] != '2')
	goto bad_rsp;
    fprintf(sp, "RCPT TO: <%s>\n", dest);
    fflush(sp);
    respond(R_STATUS, STATUS_SENDING_REQUEST, 0);
    if (readline(1, Conn, mbuf, MBSIZE) < 0)
    {
	e = errno;
	goto err_out;
    }
    if (mbuf[0] != '2')
	goto bad_rsp;
    fprintf(sp, "DATA\n");
    fflush(sp);
    respond(R_STATUS, STATUS_SENDING_REQUEST, 0);
    if (readline(1, Conn, mbuf, MBSIZE) < 0)
    {
	e = errno;
	goto err_out;
    }
    if (mbuf[0] != '3')
	goto bad_rsp;
    time(&now);
    fprintf(sp, "Date: %sTo: %s\nFrom: %s\nSubject: %s\n\n",
	    ctime(&now), dest, username, Args.Asubj);
    fflush(sp);
    while (fgets(gbuf, READ_SIZE, fp))
    {
	if (gbuf[0] == '.' && gbuf[1] == '\0')
	{
	    gbuf[1] = '.';
	    gbuf[2] = '\0';
	}
	fprintf(sp, "%s", gbuf);
    }
    fprintf(sp, ".\n");
    fflush(sp);
    fclose(fp);
    respond(R_STATUS, STATUS_WAITING_RESPONSE, 0);
    if (readline(1, Conn, mbuf, MBSIZE) < 0)
    {
	e = errno;
	goto err_out;
    }
    if (mbuf[0] != '2')
	goto bad_rsp;
    fprintf(sp, "QUIT\n");
    fflush(sp);
    closeConn(Conn);
    return 0;
}
