/*
** folder_delmsgs.c -- remove (= unlink) SELECTED messages from a folder
**
** 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 <sysexits.h>
#include <unistd.h>
#include <h/mh.h>

/*
** Unlink the SELECTED messages.
**
** If there is an error, return -1, else return 0.
*/
int
folder_delmsgs(struct msgs *mp, int hook)
{
	int msgnum, retval = 0;
	char msgpath[BUFSIZ];

	for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
		if (!is_selected(mp, msgnum)) {
			continue;
		}

		/* unselect message */
		unset_selected(mp, msgnum);

		snprintf(msgpath, sizeof (msgpath), "%s/%d",
				mp->foldpath, msgnum);

		if (hook) {
			/* Run the external hook on the message. */
			ext_hook("del-hook", msgpath, NULL);
		}

		/* just unlink the messages */
		if (unlink(msgpath) == -1) {
			admonish(msgpath, "unable to unlink");
			retval = -1;
			continue;
		}

		/* If removal was successful, decrement message count */
		unset_exists(mp, msgnum);
		mp->nummsg--;
	}

	/* Sanity check */
	if (mp->numsel != 0)
		adios(EX_SOFTWARE, NULL, "oops, mp->numsel should be 0");

	/* Mark that the sequence information has changed */
	mp->msgflags |= SEQMOD;

	return retval;
}
