aboutsummaryrefslogtreecommitdiffstats
path: root/get-contact-photos.c
blob: 3b44393b1e3ae091538591773266c048b5ca67e1 (plain) (blame)
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
/* See LICENSE file for copyright and license details. */
#include "common.h"

USAGE("[-a] contact-id ...");


int
main(int argc, char *argv[])
{
	int absolute_path = 0;
	struct passwd *user;
	struct libcontacts_contact contact;
	const char *slash = "";
	char **photos, **r, **w;
	size_t i;

	ARGBEGIN {
	case 'a':
		absolute_path = 1;
		break;
	default:
		usage();
	} ARGEND;

	if (!argc)
		usage();

	for (i = 0; argv[i]; i++)
		if (!*argv[i] || strchr(argv[i], '/'))
			usage();

	errno = 0;
	user = getpwuid(getuid());
	if (!user)
		eprintf("getpwuid: %s\n", errno ? strerror(errno) : "user does not exist");

	if (libcontacts_load_contact(*argv, &contact, user))
		eprintf("libcontacts_load_contact %s: %s\n", *argv, errno ? strerror(errno) : "contact file is malformatted");
	photos = contact.photos;
	contact.photos = NULL;
	libcontacts_contact_destroy(&contact);
	if (!photos || !*photos) {
		free(photos);
		return 0;
	}

	for (; *argv; argv++) {
		if (libcontacts_load_contact(*argv, &contact, user))
			eprintf("libcontacts_load_contact %s: %s\n", *argv, errno ? strerror(errno) : "contact file is malformatted");
		if (!contact.photos) {
			libcontacts_contact_destroy(&contact);
			for (i = 0; photos[i]; i++)
				free(photos[i]);
			free(photos);
			return 0;
		}
		for (w = r = photos; *r; r++) {
			for (i = 0; contact.photos[i]; i++)
				if (!strcmp(contact.photos[i], *r))
					break;
			if (!contact.photos[i])
				free(*r);
			else
				*w++ = *r;
		}
		*w = NULL;
		libcontacts_contact_destroy(&contact);
		if (!*photos) {
			free(photos);
			return 0;
		}
	}

	if (absolute_path && strchr(user->pw_dir, '\0')[-1] != '/')
		slash = "/";
	for (i = 0; photos[i]; i++) {
		if (photos[i][0] != '/' && absolute_path)
			printf("%s%s%s\n", user->pw_dir, slash, photos[i]);
		else if (photos[i][0])
			printf("%s\n", photos[i]);
		free(photos[i]);
	}
	free(photos);

	if (fflush(stdout) || ferror(stdout) || fclose(stdout))
		eprintf("printf:");
	return 0;
}