/*
 * 2007+ Copyright (c) Evgeniy Polyakov <johnpol@2ka.mipt.ru>
 * All rights reserved.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */

#define _GNU_SOURCE
#define __USE_FILE_OFFSET64
#define __USE_LARGEFILE64
#define _FILE_OFFSET_BITS	64

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>

#include <errno.h>
#include <fcntl.h>
#include <netdb.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <dirent.h>
#include <signal.h>

static inline void uloga(const char *f, ...)
{
	va_list ap;

	va_start(ap, f);
	vfprintf(stdout, f, ap);
	va_end(ap);

	fflush(stdout);
}

static inline void ulog(const char *f, ...)
{
	char str[64];
	struct tm tm;
	struct timeval tv;
	va_list ap;

	gettimeofday(&tv, NULL);
	localtime_r((time_t *)&tv.tv_sec, &tm);
	strftime(str, sizeof(str), "%F %R:%S", &tm);

	fprintf(stdout, "%s.%05lu ", str, tv.tv_usec);

	va_start(ap, f);
	vfprintf(stdout, f, ap);
	va_end(ap);

	fflush(stdout);
}

#define ulog_err(f, a...) ulog(f ": %s [%d].\n", ##a, strerror(errno), errno)

static void cdel_usage(char *p)
{
	fprintf(stderr, "Usage: %s -n num -d dir\n", p);
}

static int cdel_create(char *root, int num)
{
	int fd, rlen, rest, i, err;
	char name[4096], *data;

	err = mkdir(root, 0755);
	if (err && errno != EEXIST) {
		ulog_err("Failed to creat root directory %s", root);
		return -1;
	}

	rlen = snprintf(name, sizeof(name), "%s/", root);
	data = &name[rlen];
	rest = sizeof(name) - rlen;

	for (i=0; i<num; ++i) {
		snprintf(data, rest, "%016x", i);

		fd = open(name, O_RDWR | O_TRUNC | O_CREAT, 0644);
		if (fd < 0) {
			ulog_err("Failed to create file %s, i: %d/%d", name, i, num);
			return -1;
		}

		close(fd);
	}

	return 0;
}

static int do_rmdir(int dirfd, char *sub, int flags)
{
	int fd, err = 0;
	DIR *dir;
	struct dirent64 *d;

	if (flags != AT_REMOVEDIR)
		goto do_unlink;

	fd = openat(dirfd, sub, O_RDONLY);
	if (fd == -1) {
		ulog_err("Failed to open '%s' in %d", sub, dirfd);
		return -errno;
	}

	dir = fdopendir(fd);
	err = 0;

	while ((d = readdir64(dir)) != NULL) {
		if (d->d_name[0] == '.' && d->d_name[1] == '\0')
			continue;
		if (d->d_name[0] == '.' && d->d_name[1] == '.' && d->d_name[2] == '\0')
			continue;

		if (d->d_type == DT_DIR) {
			err = do_rmdir(fd, d->d_name, AT_REMOVEDIR);
			if (err)
				break;
		} else {
			err = unlinkat(fd, d->d_name, 0);
			if (err) {
				ulog_err("Failed to remove %s/%s", sub, d->d_name);
				break;
			}
		}
	}
	close(fd);
	
do_unlink:
	if (!err) {
		err = unlinkat(dirfd, sub, flags);
		if (err)
			ulog_err("Failed to remove %s", sub);
	}
	
	return err;
}

static int cdel_remove(char *root)
{
	return do_rmdir(-1, root, AT_REMOVEDIR);
}

int main(int argc, char *argv[])
{
	int ch, num = 1000, err;
	char *root = NULL;

	while ((ch = getopt(argc, argv, "n:d:h")) != -1) {
		switch (ch) {
			case 'n':
				num = atoi(optarg);
				break;
			case 'd':
				root = optarg;
				break;
			default:
				cdel_usage(argv[0]);
				return -1;
		}
	}

	if (!root) {
		fprintf(stderr, "You have to provide root dir.\n");
		cdel_usage(argv[0]);
		return -1;
	}

	ulog("Starting sequential creation of %d files in %s.\n", num, root);
	err = cdel_create(root, num);
	if (err)
		return err;
	
	ulog("Starting sequential deletion of all objects in %s.\n", root);
	err = cdel_remove(root);
	if (err)
		return err;

	ulog("Tests have been successfully completed.\n");

	return 0;
}
