From c2b33333b84dd0534b2cb153c7a9f31c354ddad4 Mon Sep 17 00:00:00 2001 From: Mattias Andrée Date: Sat, 3 Apr 2021 12:55:33 +0200 Subject: m + add more tools MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Mattias Andrée --- set-contact-groups.c | 79 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 set-contact-groups.c (limited to 'set-contact-groups.c') diff --git a/set-contact-groups.c b/set-contact-groups.c new file mode 100644 index 0000000..2b8e3c1 --- /dev/null +++ b/set-contact-groups.c @@ -0,0 +1,79 @@ +/* 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) { + free(*r); + for (w = r++; *r;) + *w++ = *r++; + *w = NULL; + if (libcontacts_save_contact(&contact, user)) { + weprintf("libcontacts_save_contact %s:", *argv); + ret = 1; + } + } else if (!remove && !*r) { + goto add_group; + } + } 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; +} -- cgit v1.2.3-70-g09d2