aboutsummaryrefslogtreecommitdiff
path: root/src/remembering-c.c
blob: 3f664735612d8fe2af145033428987118e955192 (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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#ifndef _POSIX_C_SOURCE
#define _POSIX_C_SOURCE 200809L
#endif

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

const int EXIT_ERROR = 1;
const int EXIT_USAGE = 2;

int usage(FILE *stream) {
	const char *const msg = "Usage:  remembering -p PROFILE -c COMMAND\n";
	if (fprintf(stream, msg) < 0) {
		perror("usage()");
		return -1;
	}
	return 0;
}

int help(FILE *stream) {
	const char *const msg =
		"Options:\n"
		"  -p, PROFILE    profile to be used for gathering and storing data\n"
		"  -c, COMMAND    commant to be run, reading from STDIN, writing to STDOUT\n"
		"  -h, --help     show this help\n"
		"  -V, --version  print the version number\n"
		"\nSee \"man remembering\" for more information\n";
	if (fprintf(stream, msg) < 0) {
		perror("help()");
		return -1;
	}
	return 0;
}

int version(FILE *stream) {
	const char *const msg = "remembering-" VERSION " " DATE "\n";
	if (fprintf(stream, msg) < 0) {
		perror("version()");
		return -1;
	}
	return 0;
}

int missing(FILE *stream, const char *const argument) {
	const char *const msg = "Missing option: %s\n";
	if (fprintf(stream, msg, argument) < 0) {
		perror("missing()");
		return -1;
	}
	return 0;
}

int main(int argc, char *argv[]) {
#ifdef TEST
	return EXIT_SUCCESS;
#endif

	for (int i = 0; i < argc; i++) {
		if (strcmp("--", argv[i]) == 0) {
			break;
		} else if (strcmp("--help", argv[i]) == 0) {
			if (usage(stdout)) return EXIT_ERROR;
			if (help(stdout)) return EXIT_ERROR;
			return EXIT_SUCCESS;
		} else if (strcmp("--version", argv[i]) == 0) {
			if (version(stdout)) return EXIT_ERROR;
			return EXIT_SUCCESS;
		}
	}

	int option;
	const char *profile = NULL;
	const char *command = NULL;
	while ((option = getopt(argc, argv, "p:c:hV")) != -1) {
		switch (option) {
		case 'p':
			profile = optarg;
			break;
		case 'c':
			command = optarg;
			break;
		case 'h':
			if (usage(stdout)) return EXIT_ERROR;
			if (help(stdout)) return EXIT_ERROR;
			return EXIT_SUCCESS;
		case 'V':
			if (version(stdout)) return EXIT_ERROR;
			return EXIT_SUCCESS;
		default:
			if (usage(stderr)) return EXIT_ERROR;
			return EXIT_USAGE;
		}
	}

	if (!profile) {
		if (missing(stderr, "-p PROFILE")) return EXIT_ERROR;
		if (usage(stderr)) return EXIT_ERROR;
		return EXIT_USAGE;
	}

	if (!command) {
		if (missing(stderr, "-c COMMAND")) return EXIT_ERROR;
		if (usage(stderr)) return EXIT_ERROR;
		return EXIT_USAGE;
	}

	return 0;
}