#define _ATFILE_SOURCE
#define _GNU_SOURCE
#define __USE_FILE_OFFSET64
#define __USE_LARGEFILE64
#define _FILE_OFFSET_BITS	64
#define _BSD_SOURCE

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/time.h>
#include <sys/xattr.h>

#include <fcntl.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <dirent.h>
#include <pthread.h>
#include <poll.h>

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

	fd = openat(dirfd, sub, O_RDONLY);
	if (fd == -1) {
		perror("openat");
		return -1;
	}

	dir = fdopendir(fd);
	if (dir) {
		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) {
				printf("dir  %s/%s, type: %d\n", sub, d->d_name, d->d_type);
				err = fserver_do_rmdir(fd, d->d_name, AT_REMOVEDIR);
				if (err)
					break;
			} else {
				struct stat st;

				err = fstatat(fd, d->d_name, &st, 0);

				printf("file %s/%s, type: %d, mode: %o/%x\n", sub, d->d_name, d->d_type, st.st_mode, (st.st_mode >> 12) & 15);
			}
		}
	} else {
		flags = 0;
	}

	close(fd);

	return err;
}

int main(int argc, char *argv[])
{
	int err;
	unsigned flags = 0;

#ifdef _DIRENT_HAVE_D_TYPE
	printf("Have dtype\n");
#endif
#ifdef _DIRENT_HAVE_D_NAMLEN
	printf("Have namelen\n");
#endif

	flags = AT_REMOVEDIR;

	if (argc >= 1)
		err = fserver_do_rmdir(AT_FDCWD, argv[1], flags);

	return 0;
}

