aboutsummaryrefslogtreecommitdiffstats
path: root/src/main.c
blob: 86def80ca44d4e55f3cb2c08841d96b7031395b7 (plain)
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
#include "opt.h"
#include "err.h"

#include "../reqs/simple-xdg-bdirs/simple-xdg-bdirs.h"

#include <stdbool.h>

#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main(int argc, char **argv)
{
	enum opt_command_e cmd;

	char *calpath;
	FILE *cal;

	char *ed;
	pid_t pid;
	int wstatus;

	char **rdirs, **cur;
	bool calpath_alloced = false;

	opt_parse(argc, argv);

	cmd = opt_command();

	if (opt_calpath() != NULL) {
		calpath = opt_calpath();
	} else {
		rdirs = simple_xdg_bdirs_read_dirs(SIMPLE_XDG_BDIRS_CONFIG);

		if (rdirs == NULL)
			ERR("no calendar specified, and default was not found or readable");

		calpath = simple_xdg_bdirs_fullpath_read("every/calendar", rdirs);

		for (cur = rdirs; *cur != NULL; cur++)
			free(*cur);
		free(rdirs);

		if (calpath == NULL)
			ERR("no calendar specified, and default was not found or readable");
	}

	/* edit command */
	if (cmd == OPT_COMMAND_EDIT) {
		ed = opt_editor();

		if (ed == NULL) {
			ERR("no editor specified, and $EDITOR was not found");
		}

		pid = fork();

		if (pid == 0) {
			if (execlp(ed, ed, calpath, (char*)NULL) == -1)
				exit(EXIT_FAILURE);
		} else if (pid == -1) {
			if (calpath_alloced)
				free(calpath);

			ERR("editor failed to spawn");
		} else {
			if (waitpid(pid, &wstatus, 0) == -1) {
				if (calpath_alloced)
					free(calpath);

				ERR("editor failed to spawn");
			}

			if (calpath_alloced)
				free(calpath);

			if (!WIFEXITED(wstatus) || WEXITSTATUS(wstatus))
				ERR("editor failed to spawn or exited abnormally");

			exit(EXIT_SUCCESS);
		}

		if (calpath_alloced)
			free(calpath);

		exit(EXIT_SUCCESS);
	}

	/* output commands */
	cal = fopen(calpath, "r");
	if (cal == NULL) {
		fprintf(stderr, "err: could not read calendar at `%s`\n", calpath);

		if (calpath_alloced)
			free(calpath);

		exit(EXIT_FAILURE);
	}

	if (calpath_alloced)
		free(calpath);

	if (cmd == OPT_COMMAND_CONSOLE)

	fclose(cal);
	
	return 0;
}