/*
** rmf.c -- remove 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 <h/mh.h>
#include <h/utils.h>
#include <unistd.h>
#include <dirent.h>
#include <locale.h>
#include <sysexits.h>

static struct swit switches[] = {
#define INTRSW  0
	{ "interactive", 0 },
#define NINTRSW  1
	{ "nointeractive", 2 },
#define VERSIONSW  2
	{ "Version", 0 },
#define HELPSW  3
	{ "help", 0 },
	{ NULL, 0 }
};

char *version=VERSION;

/*
** static prototypes
*/
static int rmf(char *);
static void rma(char *);


int
main(int argc, char **argv)
{
	int defolder = 0, interactive = -1;
	char *cp, *folder = NULL, newfolder[BUFSIZ];
	char buf[BUFSIZ], **argp, **arguments;

	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", cp);

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

	if (!folder) {
		folder = getcurfol();
		defolder++;
	}
	if (strcmp(toabsdir(folder), pwd()) == 0)
		adios(EX_USAGE, NULL, "You can't remove the current working directory");

	if (interactive == -1)
		interactive = defolder;

	if (strchr(folder, '/') && (*folder != '/') && (*folder != '.')) {
		strcpy(newfolder, folder);
		cp = newfolder + strlen(newfolder);
		while (cp > newfolder && *cp != '/')
			cp--;
		if (cp > newfolder)
			*cp = '\0';
		else
			strncpy(newfolder, getdeffol(), sizeof(newfolder));
	} else {
		strncpy(newfolder, getdeffol(), sizeof(newfolder));
	}

	if (interactive) {
		cp = concat("Remove folder \"", folder, "\"? ", NULL);
		if (!getanswer(cp))
			exit(EX_OK);
		mh_free0(&cp);
	}

	if (rmf(folder) == OK) {
		char *cfolder = context_find(curfolder);
		if (cfolder && strcmp(cfolder, newfolder)!=0) {
			printf("[+%s now current]\n", newfolder);
			/* update current folder */
			context_replace(curfolder, newfolder);
		}
	}
	context_save();  /* save the context file */
	return 0;
}

static int
rmf(char *folder)
{
	int i, others;
	char *maildir;
	char cur[BUFSIZ];
	struct dirent *dp;
	DIR *dd;

	switch (i = chdir(maildir = toabsdir(folder))) {
	case OK:
		if (access(".", W_OK) != NOTOK && access("..", W_OK) != NOTOK)
			break;  /* fall otherwise */

	case NOTOK:
		snprintf(cur, sizeof(cur), "atr-%s-%s", seq_cur,
				toabsdir(folder));
		if (!context_del(cur)) {
			printf("[+%s de-referenced]\n", folder);
			return OK;
		}
		advise(NULL, "you have no profile entry for the %s folder +%s",
				i == NOTOK ? "unreadable" : "read-only",
				folder);
		return NOTOK;
	}

	if ((dd = opendir(".")) == NULL)
		adios(EX_IOERR, NULL, "unable to read folder +%s", folder);
	others = 0;

	/*
	** Run the external delete hook program.
	*/

	ext_hook("del-hook", maildir, NULL);

	while ((dp = readdir(dd))) {
		switch (dp->d_name[0]) {
		case '.':
			if (strcmp(dp->d_name, ".") == 0 ||
					strcmp(dp->d_name, "..") == 0)
				continue;  /* else fall */

		case ',':
			break;

		default:
			if (m_atoi(dp->d_name))
				break;

			admonish(NULL, "file \"%s/%s\" not deleted",
					folder, dp->d_name);
			others++;
			continue;
		}
		if (unlink(dp->d_name) == NOTOK) {
			admonish(dp->d_name, "unable to unlink %s:", folder);
			others++;
		}
	}

	closedir(dd);

	/*
	** Remove any relevant private sequences
	** or attributes from context file.
	*/
	rma(folder);

	chdir("..");
	if (others == 0) {
		context_save();  /* Is this needed? meillo 2011-10 */
		fflush(stdout);  /* Is this needed? meillo 2011-10 */
		if (rmdir(maildir) != -1) {
			return OK;
		}
		admonish(maildir, "unable to remove directory");
	}

	advise(NULL, "folder +%s not removed", folder);
	return NOTOK;
}


/*
** Remove all the (private) sequence information for
** this folder from the profile/context list.
*/

static void
rma(char *folder)
{
	int alen, j, plen;
	char *cp;
	struct node *np, *pp;

	alen = strlen("atr-");
	plen = strlen(cp = mh_xstrdup(toabsdir(folder))) + 1;

	/*
	** Search context list for keys that look like
	** "atr-something-folderpath", and remove them.
	*/
	for (np = m_defs, pp = NULL; np; np = np->n_next) {
		if (strncmp(np->n_name, "atr-", alen)==0 &&
				(j = strlen(np->n_name) - plen) > alen &&
				*(np->n_name + j) == '-' &&
				strcmp(cp, np->n_name + j + 1) == 0) {
			if (!np->n_context)
				admonish(NULL, "bug: context_del(key=\"%s\")",
						np->n_name);
			if (pp) {
				pp->n_next = np->n_next;
				np = pp;
			} else {
				m_defs = np->n_next;
			}
			ctxflags |= CTXMOD;
		} else {
			pp = np;
		}
	}
	mh_free0(&cp);
}
