/*
** burst.c -- explode digests into individual 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/utils.h>
#include <unistd.h>
#include <sys/stat.h>
#include <locale.h>
#include <sysexits.h>

static struct swit switches[] = {
#define VERBSW 0
	{ "verbose", 0 },
#define NVERBSW 1
	{ "noverbose", 2 },
#define VERSIONSW 2
	{ "Version", 0 },
#define HELPSW 3
	{ "help", 0 },
	{ NULL, 0 }
};

char *version=VERSION;

static char delim3[] = "-------";

struct smsg {
	long s_start;
	long s_stop;
};

/*
** static prototypes
*/
static int find_delim(int, struct smsg *);
static void burst(struct msgs **, int, struct smsg *, int, int, char *);
static void cpybrst(FILE *, FILE *, char *, char *, int);


int
main(int argc, char **argv)
{
	int verbosw = 0;
	int msgp = 0, hi, msgnum, numburst;
	char *cp, *maildir, *folder = NULL, buf[BUFSIZ];
	char **argp, **arguments, *msgs[MAXARGS];
	struct smsg *smsgs;
	struct msgs *mp;

	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:
				adios(EX_USAGE, NULL, "-%s unknown\n", cp);

			case HELPSW:
				snprintf(buf, sizeof(buf), "%s [+folder] [msgs] [switches]", 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 VERBSW:
				verbosw++;
				continue;
			case NVERBSW:
				verbosw = 0;
				continue;
			}
		}
		if (*cp == '+' || *cp == '@') {
			if (folder)
				adios(EX_USAGE, NULL, "only one folder at a time!");
			else
				folder = mh_xstrdup(expandfol(cp));
		} else {
			msgs[msgp++] = cp;
		}
	}

	if (!msgp)
		msgs[msgp++] = seq_cur;
	if (!folder)
		folder = getcurfol();
	maildir = toabsdir(folder);

	if (chdir(maildir) == NOTOK)
		adios(EX_SOFTWARE, maildir, "unable to change directory to");

	/* read folder and create message structure */
	if (!(mp = folder_read(folder)))
		adios(EX_IOERR, NULL, "unable to read folder %s", folder);

	/* check for empty folder */
	if (mp->nummsg == 0)
		adios(EX_DATAERR, NULL, "no messages in %s", folder);

	/* parse all the message ranges/sequences and set SELECTED */
	for (msgnum = 0; msgnum < msgp; msgnum++)
		if (!m_convert(mp, msgs[msgnum]))
			exit(EX_SOFTWARE);
	seq_setprev(mp);  /* set the previous-sequence */

	smsgs = mh_xcalloc(MAXFOLDER + 2, sizeof(*smsgs));

	hi = mp->hghmsg + 1;

	/* burst all the SELECTED messages */
	for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
		if (is_selected(mp, msgnum)) {
			if ((numburst = find_delim(msgnum, smsgs)) > 0) {
				if (verbosw)
					printf("%d message%s exploded from digest %d\n", numburst, numburst > 1 ? "s" : "", msgnum);
				burst(&mp, msgnum, smsgs, numburst, verbosw, maildir);
			} else if (numburst == 0) {
				admonish(NULL, "message %d not in digest format", msgnum);
			} else {
				adios(EX_SOFTWARE, NULL, "burst() botch -- you lose big");
			}
		}
	}

	mh_free0(&smsgs);
	context_replace(curfolder, folder);

	/*
	** The first message extracted from the first digest
	** becomes the current message.
	*/
	if (hi <= mp->hghmsg) {
		seq_setcur(mp, hi);
	}

	seq_save(mp);
	context_save();
	folder_free(mp);
	return 0;
}


/*
** Scan the message and find the beginning and
** end of all the messages in the digest.
*/
static int
find_delim(int msgnum, struct smsg *smsgs)
{
	int ld3, wasdlm, msgp;
	long pos;
	char c, *msgnam;
	int cc;
	char buffer[BUFSIZ];
	FILE *in;

	ld3 = strlen(delim3);

	if ((in = fopen(msgnam = m_name(msgnum), "r")) == NULL)
		adios(EX_IOERR, msgnam, "unable to read message");

	for (msgp = 0, pos = 0L; msgp <= MAXFOLDER; msgp++) {
		while (fgets(buffer, sizeof(buffer), in) && buffer[0] == '\n')
			pos += (long) strlen(buffer);
		if (feof(in)) {
			break;
		}
		fseek(in, pos, SEEK_SET);
		smsgs[msgp].s_start = pos;

		for (c = 0; fgets(buffer, sizeof(buffer), in); c = buffer[0]) {
			if (strncmp(buffer, delim3, ld3) == 0
					&& (msgp == 1 || c == '\n')) {
				cc = getc(in);
				ungetc(cc, in);
				if (cc == '\n' || cc == EOF) {
					break;
				}
			} else
				pos += (long) strlen(buffer);
		}

		wasdlm = strncmp(buffer, delim3, ld3) == 0;
		if (smsgs[msgp].s_start != pos)
			smsgs[msgp].s_stop = (c == '\n' && wasdlm) ?
					pos - 1 : pos;
		if (feof(in)) {
			break;
		}
		pos += (long) strlen(buffer);
	}

	fclose(in);
	return (msgp > 0) ? msgp-1 : 0;  /* toss "End of XXX Digest" */
}


/*
** Burst out the messages in the digest into the folder
*/
static void
burst(struct msgs **mpp, int msgnum, struct smsg *smsgs, int numburst,
	int verbosw, char *maildir)
{
	int i, j, mode;
	char *msgnam;
	char destfil[BUFSIZ];
	FILE *in, *out;
	struct stat st;
	struct msgs *mp;

	if ((in = fopen(msgnam = m_name(msgnum), "r")) == NULL)
		adios(EX_IOERR, msgnam, "unable to read message");

	mode = fstat(fileno(in), &st) != NOTOK ?
			(int)(st.st_mode & 0777) : m_gmprot();
	mp = *mpp;

	/*
	** Ensure we have enough space in the folder
	** structure for all the new messages.
	*/
	if ((mp->hghmsg + numburst > mp->hghoff) && !(mp = folder_realloc(mp,
			mp->lowoff, mp->hghmsg + numburst)))
		adios(EX_OSERR, NULL, "unable to allocate folder storage");
	*mpp = mp;

	/*
	** At this point, there is an array of numburst smsgs, each
	** element of which contains the starting and stopping offsets
	** (seeks) of the message in the digest. Go through the message
	** numbers. Ignore smsgs[0], which is the table of contents.
	*/
	for (j=1, i=mp->hghmsg+1; j<=numburst; j++, i++) {
		snprintf(destfil, sizeof destfil, "%s/%d", maildir, i);
		if (!(out = fopen(destfil, "w"))) {
			adios(EX_IOERR, destfil, "unable to open");
		}
		if (verbosw) {
			printf("message %d of digest %d becomes message %d\n",
					j, msgnum, i);
		}
		chmod(destfil, mode);
		fseek(in, smsgs[j].s_start, SEEK_SET);
		cpybrst(in, out, msgnam, destfil,
				(int) (smsgs[j].s_stop - smsgs[j].s_start));
		fclose(out);
		mp->hghmsg++;
		mp->nummsg++;
		/*
		** Bursting each message is equivalent to adding a
		** new message from the point of view of the external hooks.
		*/
		ext_hook("add-hook", destfil, NULL);
		copy_msg_flags(mp, i, msgnum);
		mp->msgflags |= SEQMOD;
	}
	fclose(in);
}


/*
** Copy a message which is being burst out of a digest.
** It will remove any "dashstuffing" in the message.
*/
static void
cpybrst(FILE *in, FILE *out, char *ifile, char *ofile, int len)
{
	int c;
	enum { S1, S2, S3 } state;

	for (state = S1; (c = fgetc(in)) != EOF && len > 0; len--) {
		if (c == 0)
			continue;
		switch (state) {
		case S1:
			switch (c) {
			case '-':
				state = S3;
				break;

			default:
				state = S2;
			case '\n':
				fputc(c, out);
				break;
			}
			break;

		case S2:
			switch (c) {
			case '\n':
				state = S1;
			default:
				fputc(c, out);
				break;
			}
			break;

		case S3:
			switch (c) {
			case ' ':
				state = S2;
				break;

			default:
				state = (c == '\n') ? S1 : S2;
				fputc('-', out);
				fputc(c, out);
				break;
			}
			break;
		}
	}

	if (ferror(in) && !feof(in))
		adios(EX_IOERR, ifile, "error reading");
	if (ferror(out))
		adios(EX_IOERR, ofile, "error writing");
}
