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

USAGE("[-a | -u] contact-id");


int
main(int argc, char *argv[])
{
	int append = 0, unset = 0;
	struct passwd *user;
	struct libcontacts_contact contact;
	size_t size = 0, len = 0;
	ssize_t r;

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

	if (argc != 1 || (append && unset))
		usage();

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

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

	if (libcontacts_load_contact(argv[0], &contact, user))
		eprintf("libcontacts_load_contact %s: %s\n", argv[0], errno ? strerror(errno) : "contact file is malformatted");

	if (contact.notes) {
		if (append) {
			len = strlen(contact.notes);
			size = len + 1;
		} else {
			free(contact.notes);
			contact.notes = NULL;
		}
	}
	if (!unset) {
		for (;;) {
			if (len == size)
				contact.notes = erealloc(contact.notes, size += 512);
			r = read(STDIN_FILENO, &contact.notes[len], size - len);
			if (r <= 0) {
				if (!r)
					break;
				eprintf("read <stdin>:");
			}
			len += (size_t)r;
		}
		if (size) {
			if (len == size)
				contact.notes = erealloc(contact.notes, size += 1);
			contact.notes[len] = '\0';
		}
	}

	if (libcontacts_save_contact(&contact, user))
		eprintf("libcontacts_save_contact %s:", argv[0]);

	libcontacts_contact_destroy(&contact);

	return 0;
}