
/*
 * folder_delmsgs.c -- "remove" SELECTED messages from a folder
 *
 * $Id$
 */

#include <h/mh.h>

/*
 * 1) If we are using an external rmmproc, then exec it.
 * 2) Else if rename_msgs is non-zero, then rename messages by
 *    prefixing name with standard prefix.
 * 3) Else unlink SELECTED messages.
 *
 * If there is an error, return -1, else return 0.
 */

int
folder_delmsgs (struct msgs *mp, int rename_msgs)
{
    pid_t pid;
    int msgnum, vecp, retval = 0;
    char buf[100], *dp, **vec;

    for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
	if (is_selected (mp, msgnum)) {
	    unset_exists (mp, msgnum);
	}
    }
    mp->msgflags |= SEQMOD;

    /* If "rmmproc" is defined, use it to remove messages */
    if (rmmproc) {
	if (mp->numsel > MAXARGS - 2)
	    adios (NULL, "more than %d messages for %s exec", MAXARGS - 2,
		   rmmproc);
	vec = (char **) calloc ((size_t) (mp->numsel + 2), sizeof(*vec));
	if (vec == NULL)
	    adios (NULL, "unable to allocate exec vector");
	vecp = 1;
	for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
	    if (is_selected (mp, msgnum) &&
		!(vec[vecp++] = strdup (m_name (msgnum))))
		adios (NULL, "strdup failed");
	}
	vec[vecp] = NULL;

	fflush (stdout);
	vec[0] = r1bindex (rmmproc, '/');

	switch (pid = vfork()) {
	case NOTOK:
	    advise ("fork", "unable to");
	    return NOTOK;

	case OK:
	    execvp (rmmproc, vec);
	    fprintf (stderr, "unable to exec ");
	    perror (rmmproc);
	    _exit (-1);

	default:
	    return (pidwait (pid, NOTOK));
	}
    }

    /* Either rename or unlink the SELECTED messages */
    for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
	if (is_selected (mp, msgnum)) {
	    dp = m_name (msgnum);
	    if (rename_msgs) {
		/* rename messages with standard prefix */
		strcpy (buf, m_backup (dp));
		if (rename (dp, buf) == NOTOK) {
		    admonish (buf, "unable to rename %s to", dp);
		    retval = -1;
		}
	    } else {
		/* or just unlink the selected messages */
		if (unlink (dp) == NOTOK) {
		    admonish (dp, "unable to unlink");
		    retval = -1;
		}
	    }
	}
    }

    return retval;
}
