/*
** makedir.c -- make a directory
**
** 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.
*/

/*
** Modified to try recursive create.
*/

#include <h/mh.h>
#include <errno.h>
#include <sys/param.h>
#include <sys/file.h>
#include <sys/stat.h>

int
makedir(char *dir)
{
	char path[PATH_MAX];
	char *cp;
	int had_an_error = 0;
	mode_t folder_perms, saved_umask;
	char* c;

	context_save();  /* save the context file */
	fflush(stdout);

	if (!(cp = context_find("folder-protect")) || !*cp) {
		cp = foldprot;
	}
	folder_perms = strtoul(cp, NULL, 8);

	/*
	** Folders have definite desired permissions that are set -- we
	** don't want to interact with the umask.  Clear it temporarily.
	*/
	saved_umask = umask(0);

	c = strncpy(path, dir, sizeof(path));

	while (!had_an_error && (c = strchr((c + 1), '/')) != NULL) {
		*c = '\0';
		/* Create an outer directory. */
		if (mkdir(path, folder_perms) == -1 &&
				errno != EEXIST) {
			advise(dir, "unable to create directory");
			had_an_error = 1;
		}
		*c = '/';
	}

	/*
	** Create the innermost nested subdirectory of the
	** path we're being asked to create.
	*/
	if (!had_an_error && mkdir(dir, folder_perms)==-1) {
		advise(dir, "unable to create directory");
		had_an_error = 1;
	}
	umask(saved_umask);  /* put the user's umask back */

	return (had_an_error) ? 0 : 1;
}
