summary refs log tree commit diff
path: root/notemap.c
blob: fbb6e8d74c49f7f09d47496b9d68227a3fa6270f (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
/* Copyright (C) 2020  C. McEnroe <june@causal.agency>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

#include <err.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <sysexits.h>
#include <unistd.h>

typedef unsigned char byte;

static const char *uuidGen(void) {
	byte uuid[16];
	arc4random_buf(uuid, sizeof(uuid));
	uuid[6] &= 0x0F;
	uuid[6] |= 0x40;
	uuid[8] &= 0x3F;
	uuid[8] |= 0x80;

	static char str[sizeof("00000000-0000-0000-0000-000000000000")];
	snprintf(
		str, sizeof(str),
		"%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
		uuid[0], uuid[1], uuid[2], uuid[3],
		uuid[4], uuid[5], uuid[6], uuid[7],
		uuid[8], uuid[9], uuid[10], uuid[11],
		uuid[12], uuid[13], uuid[14], uuid[15]
	);
	return str;
}

int main(int argc, char *argv[]) {
	const char *path = ".notemap";
	bool add = false;

	int opt;
	while (0 < (opt = getopt(argc, argv, "am:"))) {
		switch (opt) {
			break; case 'a': add = true;
			break; case 'm': path = optarg;
			break; default:  return EX_USAGE;
		}
	}

	if (add) {
		FILE *map = fopen(path, "a");
		if (!map) err(EX_CANTCREAT, "%s", path);
		for (int i = optind; i < argc; ++i) {
			if (access(argv[i], R_OK)) err(EX_NOINPUT, "%s", argv[i]);
			fprintf(map, "%s %s\n", uuidGen(), argv[i]);
			if (ferror(map)) err(EX_IOERR, "%s", path);
		}
		int error = fclose(map);
		if (error) err(EX_IOERR, "%s", path);
	}
}