/*
** rcvdist.c -- asynchronously redistribute messages
**
** This code is Copyright (c) 2002, by the authors of nmh.  See the
** COPYRIGHT file in the root directory of the nmh distribution for
** complete copyright information.
*/

#include <h/mh.h>
#include <h/fmt_scan.h>
#include <h/rcvmail.h>
#include <h/tws.h>
#include <h/utils.h>
#include <unistd.h>
#include <sys/stat.h>
#include <locale.h>
#include <sysexits.h>

static struct swit switches[] = {
#define FORMSW  0
	{ "form formfile",  0 },
#define VERSIONSW  1
	{ "Version", 0 },
#define HELPSW  2
	{ "help", 0 },
	{ NULL, 0 }
};

char *version=VERSION;

static char backup[BUFSIZ] = "";
static char drft[BUFSIZ] = "";
static char tmpfil[BUFSIZ] = "";

/*
** prototypes
*/
static void rcvdistout(FILE *, char *, char *);
void unlink_done();


int
main(int argc, char **argv)
{
	int vecp = 1;
	char *addrs = NULL, *cp, *form = NULL, buf[BUFSIZ];
	char **argp, **arguments, *vec[MAXARGS];
	FILE *fp;
	char *tfile = NULL;

	if (atexit(unlink_done) != 0) {
		adios(EX_OSERR, NULL, "atexit failed");
	}

	setlocale(LC_ALL, "");
	invo_name = mhbasename(argv[0]);

	/* read user profile/context */
	context_read();

	arguments = getarguments(invo_name, argc, argv, 1);
	argp = arguments;

	while ((cp = *argp++)) {
		if (*cp == '-') {
			switch (smatch(++cp, switches)) {
			case AMBIGSW:
				ambigsw(cp, switches);
				exit(EX_USAGE);
			case UNKWNSW:
				vec[vecp++] = --cp;
				continue;

			case HELPSW:
				snprintf(buf, sizeof(buf), "%s [switches] [switches for spost] address ...", invo_name);
				print_help(buf, switches, 1);
				exit(argc == 2 ? EX_OK : EX_USAGE);
			case VERSIONSW:
				print_version(invo_name);
				exit(argc == 2 ? EX_OK : EX_USAGE);

			case FORMSW:
				if (!(form = *argp++) || *form == '-') {
					adios(EX_USAGE, NULL, "missing argument to %s",
							argp[-2]);
				}
				continue;
			}
		}
		addrs = addrs ? add(cp, add(", ", addrs)) : mh_xstrdup(cp);
	}

	if (!addrs) {
		adios(EX_USAGE, NULL, "usage: %s [switches] [switches for spost] address ...", invo_name);
	}

	umask(~m_gmprot());

	tfile = m_mktemp2(NULL, invo_name, NULL, &fp);
	if (tfile == NULL) adios(EX_CANTCREAT, "rcvdist", "unable to create temporary file");
	strncpy(tmpfil, tfile, sizeof(tmpfil));

	cpydata(fileno(stdin), fileno(fp), "message", tmpfil);
	fseek(fp, 0L, SEEK_SET);

	tfile = m_mktemp2(NULL, invo_name, NULL, NULL);
	if (tfile == NULL) adios(EX_CANTCREAT, "forw", "unable to create temporary file");
	strncpy(drft, tfile, sizeof(tmpfil));

	rcvdistout(fp, form, addrs);
	fclose(fp);

	if (distout(drft, tmpfil, backup) == NOTOK) {
		exit(EX_IOERR);
	}

	vec[0] = "spost";
	vec[vecp++] = "-dist";
	vec[vecp++] = drft;
	vec[vecp] = NULL;

	execvp(*vec, vec);
	fprintf(stderr, "unable to exec ");
	perror(*vec);
	_exit(EX_OSERR);
	return 0;  /* dead code to satisfy the compiler */
}

/* very similar to routine in replsbr.c */

static struct format *fmt;

static int ncomps = 0;

static int dat[5];

static char *addrcomps[] = {
	"from",
	"sender",
	"reply-to",
	"to",
	"cc",
	"bcc",
	"resent-from",
	"resent-sender",
	"resent-reply-to",
	"resent-to",
	"resent-cc",
	"resent-bcc",
	NULL
};


static void
rcvdistout(FILE *inb, char *form, char *addrs)
{
	int char_read = 0, format_len, i;
	enum state state;
	struct field f = {{0}};
	char **ap;
	char *cp, *scanl;
	struct comp *cptr;
	FILE *out;

	if (!(out = fopen(drft, "w"))) {
		adios(EX_CANTCREAT, drft, "unable to create");
	}

	/* get new format string */
	cp = new_fs(form ? form : rcvdistcomps, NULL);
	format_len = strlen(cp);
	ncomps = fmt_compile(cp, &fmt) + 1;

	for (ap = addrcomps; *ap; ap++) {
		FINDCOMP(cptr, *ap);
		if (cptr) {
			cptr->c_type |= CT_ADDR;
		}
	}

	FINDCOMP(cptr, "addresses");
	if (cptr) {
		cptr->c_text = addrs;
	}
	state = FLD2;
	while (1) {
		state = m_getfld2(state, &f, inb);
		switch (state) {
		case FLD2:
			if ((cptr = wantcomp[CHASH(f.name)])) {
				do {
					if (mh_strcasecmp(f.name, cptr->c_name)!=0) {
						continue;
					}
					char_read += strlen(f.value);
					if (!cptr->c_text) {
						cptr->c_text = mh_xstrdup(f.value);
					} else {
						cp = cptr->c_text;
						i = strlen(cp) - 1;
						if (cp[i] == '\n') {
							if (cptr->c_type & CT_ADDR) {
								cp[i] = 0;
								cp = add(",\n\t", cp);
							} else {
								cp = add("\t", cp);
							}
						}
						cptr->c_text = add(f.value, cp);
					}
					break;
				} while ((cptr = cptr->c_next));
			}
			break;

		case LENERR2:
		case FMTERR2:
		case IOERR2:
		case BODY2:
		case FILEEOF2:
			goto finished;

		default:
			adios(EX_SOFTWARE, NULL, "m_getfld() returned %d", state);
		}
	}
finished: ;

	i = format_len + char_read + 256;
	scanl = mh_xcalloc(i + 2, sizeof(char));
	dat[0] = dat[1] = dat[2] = dat[4] = 0;
	dat[3] = OUTPUTLINELEN;
	fmt_scan(fmt, scanl, i, dat);
	fputs(scanl, out);

	if (ferror(out)) {
		adios(EX_IOERR, drft, "error writing");
	}
	fclose(out);

	mh_free0(&scanl);
}


void
unlink_done()
{
	if (*backup) {
		unlink(backup);
	}
	if (*drft) {
		unlink(drft);
	}
	if (*tmpfil) {
		unlink(tmpfil);
	}
}
