summaryrefslogtreecommitdiffstats
path: root/aports-cache.c
blob: b0dfdf0806047929f32e056af001fdc03c567386 (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
#include <sys/stat.h>
#include <sys/types.h>

#include <errno.h>
#include <dirent.h>
#include <err.h>
#include <fcntl.h>
#include <getopt.h>
#include <limits.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#ifdef DEBUG
#define debug_printf(args...) fprintf(stderr, ## args)
#else
#define debug_printf(args...)
#endif

int is_newer(struct timespec a, struct timespec b)
{
	return (a.tv_sec == b.tv_sec) ?  a.tv_nsec > b.tv_nsec : a.tv_sec > b.tv_sec;
}

int cache_invalid(int dirfd, const char *filename)
{
	struct stat cache;
	DIR *dir;
	struct dirent *ent;
	int r = 0;

	if (fstatat(dirfd, filename, &cache, 0) == -1)
		return 1;

	dir = fdopendir(dirfd);
	if (dir == NULL)
		err(1, "fdopendir");
	
	while(1) {
		char buf[PATH_MAX];
		struct stat apkbuild;

		errno = 0;
		ent = readdir(dir);
		if (ent == NULL) {
			if (errno != 0)
				err(1, "readdir");
			break;
		}

		if (ent->d_name[0] == '.')
			continue;

		snprintf(buf, sizeof(buf), "%s/APKBUILD", ent->d_name);
		if (fstatat(dirfd, buf, &apkbuild, 0) == -1) {
			warn("%s", buf);
			continue;
		}

		if (is_newer(apkbuild.st_mtim, cache.st_mtim)) {
			debug_printf("%s\n", buf);
			r = 1;
			break;
		}
	}

	closedir(dir);
	return r;
}

int main(int argc, char *argv[])
{
	static struct option opts[] = {
		{"verbose",	no_argument,	0, 'v' },
		{"force",	no_argument,	0, 'f' },
		{ 0, 0, 0, 0}
	};
	int i, c, verbose=0;
	const char *cachefile = ".aports.cache.json";
	char dirpath_buf[PATH_MAX];
	char *dirpath = dirpath_buf;
	int dirfd;

	while ((c = getopt_long(argc, argv, "fv", opts, &i)) != -1) {
		switch(c) {
		case 'v':
			verbose = 1;
			break;
		}
	}
	if (verbose)
		printf("optind=%i, argc=%i\n", optind, argc);

	if (optind < argc) {
		dirpath = argv[optind];
	} else {
		dirpath = getcwd(dirpath_buf, sizeof(dirpath_buf));
	}	
	
	dirfd = open(dirpath, O_DIRECTORY);
	if (dirfd < 0)
		err(1, "%s", dirpath);

	if (cache_invalid(dirfd, cachefile))
		printf("refresh\n");	

	return 0;
}