aboutsummaryrefslogtreecommitdiffstats
path: root/set-contact-groups.c
blob: f0408c5f343cb2bfb1da58659ea4a17c497117b9 (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
/* See LICENSE file for copyright and license details. */
#include "common.h"

USAGE("[-u] contact-id ... group");


int
main(int argc, char *argv[])
{
	int remove = 0;
	struct passwd *user;
	struct libcontacts_contact contact;
	char *group, **r, **w;
	int ret = 0;
	size_t i;

	ARGBEGIN {
	case 'u':
		remove = 1;
		break;
	default:
		usage();
	} ARGEND;

	if (argc < 2)
		usage();

	group = argv[--argc];
	argv[argc] = NULL;

	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");

	for (; *argv; argv++) {
		if (libcontacts_load_contact(*argv, &contact, user)) {
			weprintf("libcontacts_load_contact %s: %s\n", *argv,
			         errno ? strerror(errno) : "contact file is malformatted");
			ret = 1;
			continue;
		}
		if (contact.groups) {
			for (i = 0; contact.groups[i]; i++)
				if (!strcmp(contact.groups[i], group))
					break;
			r = &contact.groups[i];
			if (!remove && !*r)
				goto add_group;
			if (remove && *r) {
				free(*r);
				for (w = r++; (*w++ = *r++););
				if (libcontacts_save_contact(&contact, user)) {
					weprintf("libcontacts_save_contact %s:", *argv);
					ret = 1;
				}
			}
		} else if (!remove) {
			i = 0;
		add_group:
			contact.groups = erealloc(contact.groups, (i + 2) * sizeof(*contact.groups));
			contact.groups[i + 1] = NULL;
			contact.groups[i] = group;
			if (libcontacts_save_contact(&contact, user)) {
				weprintf("libcontacts_save_contact %s:", *argv);
				ret = 1;
			}
			contact.groups[i] = NULL;
		}
		libcontacts_contact_destroy(&contact);
	}

	return ret;
}