aboutsummaryrefslogtreecommitdiffstats
path: root/get-contact-organisations.c
blob: ae236dbf715708222bfec3be8a6b86ea74ff0a5f (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("[-o organisation] [-t title] [-OT] contact-id ...");


int
main(int argc, char *argv[])
{
	int display_org = 0, display_title = 0;
	struct passwd *user;
	struct libcontacts_contact contact;
	struct libcontacts_organisation **orgs, *org;
	const char *lookup_org = NULL, *lookup_title = NULL;
	int ret = 0;
	size_t i;

	ARGBEGIN {
	case 'o':
		if (lookup_org)
			usage();
		lookup_org = ARG();
		break;
	case 't':
		if (lookup_title)
			usage();
		lookup_title = ARG();
		break;
	case 'O':
		display_org = 1;
		break;
	case 'T':
		display_title = 1;
		break;
	default:
		usage();
	} ARGEND;

	if (!argc)
		usage();

	if (lookup_org && !lookup_title && !display_org && !display_title)
		display_title = 1;
	if (lookup_title && !lookup_org && !display_org && !display_title)
		display_org = 1;

	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 ((orgs = contact.organisations)) {
			for (; (org = *orgs); orgs++) {
				if (lookup_org && strcmpnul(org->organisation, lookup_org))
					continue;
				if (lookup_title && strcmpnul(org->title, lookup_title))
					continue;
				if (lookup_org && lookup_title && !display_org && !display_title) {
					printf("%s\n", *argv);
					continue;
				}
				if (argc > 1)
					printf("%s: ", *argv);
				if (!display_org == !display_title)
					printf("%s: %s\n", org->organisation, org->title);
				else if (display_title)
					printf("%s\n", org->title);
				else
					printf("%s\n", org->organisation);
			}
		}
		libcontacts_contact_destroy(&contact);
	}

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