/*
 * Handle starting up the mail command and piping the 822 headers
 * and other data to it.
 */

#include "gup.h"


FILE	*
mail_open(open_now, to, command, headers)

    int		open_now;
    char	*to;
    char	*command;
    char	*headers;

{
    FILE	*fp;
    FILE	*hdr_fp;
    char	lbuf[MAX_LINE_SIZE];

static	char	*m_to = NULL;
static	char	*m_command = NULL;
static	char	*m_headers = NULL;

/* Stash variables as they are defined */

    if (to) m_to = xstrdup(to);
    if (command) m_command = xstrdup(command);
    if (headers) m_headers = xstrdup(headers);

    if (!open_now) return NULL;

    if (!m_command)
	gupout(1, "Install error. No mail command supplied");

    fp = popen(m_command, "w");
    if (!fp) {
	sprintf(msg, "Could not open a pipe to '%s'", m_command);
	gupout(1, msg);
    }

/*
 * Write order is: TO: , supplied headers file, blank line.
 *
 * Note that the headers are expected to contain reply-to, Subject and
 * such, but can be empty or non-existant for sendmail. Furthermore,
 * there is no reason why a preceding blab of text cannot go in there
 * too!
 */

    if (m_to) fprintf(fp, "TO: %s\n", m_to);

    if (m_headers) {
	hdr_fp = fopen(m_headers, "r");
	if (hdr_fp) {
	    while (fgets(lbuf, sizeof(lbuf), hdr_fp)) {
		fputs(lbuf, fp);
	    }
	    fclose(hdr_fp);
	}
	else {
	    sprintf(msg, "Could not open '%s'", m_headers);
	    logit(L_LOG, "WARNING", msg);
	}
    }

    fputs("\n\n", fp);	/* End of headers for certain */

    return fp;
}


extern	void
mail_close(fp)

    FILE	*fp;
{
#if 0
    /* get rid of the dup2()ed descriptor, otherwise pclose() will hang */
    close(fileno(stdout));
#endif

    if (pclose(fp) == -1)
	gupout(1, "pclose() of mail command failed");
}
