/*
 * Copyright (C) 2005-2006 Anselm R. Garbe <garbeam at gmail dot com>
 * Copyright (C) 2005-2007 Nico Golde <nico at ngolde dot de>
 *
 * Modifications: Copyright (C) 2008 Miriam Ruiz <little_miry@yahoo.es>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */

/*
 * http://code.suckless.org/hg/ii/file/06f79c8e3814/ii.c create_dir_tree()
 * http://nion.modprobe.de/blog/archives/357-Recursive-directoriy-creation.html
 */

/*
 * gcc -Wall -o recursive_mkdir recursive_mkdir.c -DTEST_RECURSIVE_MKDIR
 */
 
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <limits.h>
#include <pwd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/types.h>

int xdgMakeRecursiveDir(const char *path, mode_t mode)
{
	char tmp_path[PATH_MAX];
	char *tmp_pnt = NULL;
	size_t len;

	len = strlen(path);
	if (len >= PATH_MAX)
	{
		errno = ENAMETOOLONG;
		return -1;
	}
	strcpy(tmp_path, path);
	if (tmp_path[len - 1] == '/')
		tmp_path[len - 1] = '\0';
	if (!tmp_path[0])
		return 0;
	for (tmp_pnt = tmp_path; *tmp_pnt; tmp_pnt++)
	{
		if (*tmp_pnt == '/')
		{
			*tmp_pnt = '\0';
			if (mkdir(tmp_path, mode) == -1)
				return -1;
			*tmp_pnt = '/';
		}
	}
	if (mkdir(tmp_path, mode) == -1)
		return -1;
	return 0;
}

#ifdef TEST_RECURSIVE_MKDIR
int main(int argc, const char *argv[])
{
	if (argc != 2)
	{
		fprintf(stderr, "Usage: %s [filename]\n", argv[0]);
		return 0;
	}
	if (xdgMakeRecursiveDir(argv[1], S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH ))
	{
		fprintf(stderr, "Error: %s\n", strerror(errno));
	}
	return 0;
}
#endif

