/*
** mhmail.c -- simple mail program
**
** 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/signals.h>
#include <h/utils.h>
#include <signal.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <locale.h>
#include <sysexits.h>

static struct swit switches[] = {
#define BODYSW  0
	{ "bodytext text", 0 },
#define CCSW  1
	{ "cc addrs ...", 0 },
#define FROMSW  2
	{ "from addr", 0 },
#define SUBJSW  3
	{ "subject text", 0 },
#define VERSIONSW  4
	{ "Version", 0 },
#define HELPSW  5
	{ "help", 0 },
	{ NULL, 0 }
};

char *version=VERSION;

static char tmpfil[BUFSIZ];

/*
** static prototypes
*/
static void intrser(int);


int
main(int argc, char **argv)
{
	int status, iscc = 0, nvec;
	char *cp, *tolist = NULL, *cclist = NULL, *subject = NULL;
	char *from = NULL, *body = NULL, **argp, **arguments;
	char *vec[5], buf[BUFSIZ];
	FILE *out;
	char *tfile = NULL;

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

	/* Without arguments, exit. */
	if (argc == 1) {
		adios(EX_USAGE, NULL, "no interactive mail shell. Use inc/scan/show instead.");
	}

	context_read();

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

	while ((cp = *argp++)) {
		if (*cp == '-') {
			switch (smatch(++cp, switches)) {
			case AMBIGSW:
				ambigsw(cp, switches);
				exit(EX_USAGE);
			case UNKWNSW:
				adios(EX_USAGE, NULL, "-%s unknown", cp);

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

			case FROMSW:
				if (!(from = *argp++) || *from == '-')
					adios(EX_USAGE, NULL, "missing argument to %s",
							argp[-2]);
				continue;

			case BODYSW:
				if (!(body = *argp++) || *body == '-')
					adios(EX_USAGE, NULL, "missing argument to %s",
							argp[-2]);
				continue;

			case CCSW:
				iscc++;
				continue;

			case SUBJSW:
				if (!(subject = *argp++) || *subject == '-')
					adios(EX_USAGE, NULL, "missing argument to %s",
							argp[-2]);
				continue;
			}
		}
		if (iscc)
			cclist = cclist ? add(cp, add(", ", cclist)) :
					mh_xstrdup(cp);
		else
			tolist = tolist ? add(cp, add(", ", tolist)) :
					mh_xstrdup(cp);
	}

	if (tolist == NULL)
		adios(EX_USAGE, NULL, "usage: %s addrs ... [switches]", invo_name);

	tfile = m_mktemp2("/tmp/", invo_name, NULL, &out);
	if (tfile == NULL)
		adios(EX_CANTCREAT, "mhmail", "unable to create temporary file");
	chmod(tfile, 0600);
	strncpy(tmpfil, tfile, sizeof(tmpfil));

	SIGNAL2(SIGINT, intrser);

	fprintf(out, "To: %s\n", tolist);
	if (cclist)
		fprintf(out, "Cc: %s\n", cclist);
	if (subject)
		fprintf(out, "Subject: %s\n", subject);
	if (from)
		fprintf(out, "From: %s\n", from);
	fputs("\n", out);

	if (body) {
		fprintf(out, "%s", body);
		if (*body && body[strlen(body) - 1] != '\n')
			fputs("\n", out);
	} else {
		int empty = 1;

		while (fgets(buf, sizeof buf, stdin)) {
			if (buf[0]=='.' && buf[1]=='\n') {
				/* A period alone on a line means EOF. */
				break;
			}
			empty = 0;
			if (fputs(buf, out) == EOF) {
				adios(EX_IOERR, tmpfil, "error writing");
			}
		}
		if (empty) {
			unlink(tmpfil);
			adios(EX_DATAERR, NULL, "not sending message with empty body");
		}
	}
	fclose(out);

	nvec = 0;
	vec[nvec++] = "spost";
	vec[nvec++] = tmpfil;
	vec[nvec] = NULL;

	if ((status = execprog(*vec, vec))) {
		/* spost failed, save draft as dead.letter */
		int in, out;

		in = open(tmpfil, O_RDONLY);
		out = creat("dead.letter", 0600);
		if (in == -1 || out == -1) {
			fprintf(stderr, "Letter left at %s.\n",
					tmpfil);
			exit(status);
		}
		cpydata(in, out, tmpfil, "dead.letter");
		close(in);
		close(out);
		fprintf(stderr, "Letter saved in dead.letter\n");
	}
	unlink(tmpfil);
	exit(status);
}


static void
intrser(int i)
{
	unlink(tmpfil);
	_exit(EX_IOERR);
}

