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

USAGE("[-o organisation] [-t title] [-OT]");


int
main(int argc, char *argv[])
{
	int display_organisation = 0, display_title = 0;
	struct passwd *user;
	struct libcontacts_contact **contacts;
	struct libcontacts_organisation **orgs, *org;
	char *organisation = NULL, *title = NULL;
	size_t i;

	ARGBEGIN {
	case 'o':
		if (organisation)
			usage();
		organisation = ARG();
		break;
	case 't':
		if (title)
			usage();
		title = ARG();
		break;
	case 'O':
		display_organisation = 1;
		break;
	case 'T':
		display_title = 1;
		break;
	default:
		usage();
	} ARGEND;

	if (argc)
		usage();

	if (!organisation && !title && !display_organisation && !display_title)
		display_organisation = 1;

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

	if (libcontacts_load_contacts(&contacts, user))
		eprintf("libcontacts_load_contacts:");
	for (i = 0; contacts[i]; i++) {
		if ((orgs = contacts[i]->organisations)) {
			for (; (org = *orgs); orgs++) {
				if (organisation && strcmpnul(org->organisation, organisation))
					continue;
				if (title && strcmpnul(org->title, title))
					continue;
				if (display_organisation && display_title) {
					printf("%s (%s: %s)\n", contacts[i]->id, org->organisation, org->title);
				} else if (display_organisation) {
					printf("%s (%s)\n", contacts[i]->id, org->organisation);
				} else if (display_title) {
					printf("%s (%s)\n", contacts[i]->id, org->title);
				} else {
					printf("%s\n", contacts[i]->id);
					break;
				}
			}
		}
		libcontacts_contact_destroy(contacts[i]);
		free(contacts[i]);
	}
	free(contacts);

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

	return 0;
}