summaryrefslogtreecommitdiffstats
path: root/community-scripts/rename/atomic/bug1034/gt_init.c
blob: f3dadf0361ac62e8024c92b04caf729894bfaf88 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <fcntl.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "gt.h"

static void
usage(char *progname)
{
	fprintf(stderr, "usage: %s node_count\n", progname);
	exit(1);
}

// rm -rf
static void
delete_tree(char *rootpath)
{
	int retval;
	struct stat statbuf;

	retval = lstat(rootpath, &statbuf);
	if (retval < 0) {
		return;
	}

	if (S_ISDIR(statbuf.st_mode)) {
		DIR *dir;
		struct dirent *dent;
		char pathbuf[PATH_MAX];

		dir = opendir(rootpath);
		while ((dent = readdir(dir)) != NULL) {
			if (0 == strcmp(".", dent->d_name)) {
				continue;
			}
			if (0 == strcmp("..", dent->d_name)) {
				continue;
			}
			snprintf(pathbuf, sizeof(pathbuf),
				"%s/%s", rootpath, dent->d_name);
			delete_tree(pathbuf);
		}
		closedir(dir);

		(void)rmdir(rootpath);
	} else {
		(void)unlink(rootpath);
	}
}

static void
create_subdir(char *dirpath)
{
	int i;

	mkdir(dirpath, 0775);

	for (i = 0; i < SUBDIR_FILES; i++) {
		char pathbuf[PATH_MAX];
		int fd;

		snprintf(pathbuf, sizeof(pathbuf),
			"%s/WA_RC_%d", dirpath, i);
		fd = open(pathbuf, O_RDWR|O_CREAT, 0664);
		write(fd, pathbuf, strlen(pathbuf));
		close(fd);
	}
}

static void
create_tree(char *rootpath, int node_count)
{
	int n;

	mkdir(rootpath, 0775);

	for (n = 1; n <= node_count; n++) {
		char pathbuf[PATH_MAX];
		int fd;

		snprintf(pathbuf, sizeof(pathbuf),
			"%s/%d", rootpath, n);
		mkdir(pathbuf, 0775);
		create_subdir(pathbuf);
	}
}

int
main(int argc, char **argv)
{
	char *arg_ptr;
	long node_count;

	if (argc != 2) {
		usage(argv[0]);
	}

	node_count = strtol(argv[1], &arg_ptr, 10);
	if (*arg_ptr != '\0') {
		usage(argv[0]);
	}

	delete_tree(BASE_PATH);

	create_tree(BASE_PATH, node_count);

	exit(0);
}