aboutsummaryrefslogtreecommitdiffstats
path: root/src/main.c
blob: e10b7a74332a4c7d07269600834f6059ccf6b930 (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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
#include "opt.h"
#include "err.h"
#include "calendar.h"
#include "print.h"

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

#include <stdbool.h>
#include <limits.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 *calf;
	struct calendar_s cal;

	char *ed;
	pid_t pid;
	int wstatus;

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

	if ((unsigned long)INT_MAX < (unsigned long)2147483647) {
		ERR(
			"%s does not work appropriately on systems where `int` < 32 bits",
			argv[0]
		);
	}

	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/cal.every", 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");

		calpath_alloced = true;
	}

	/* 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);
	}

	/* parse calendar */

	calf = fopen(calpath, "r");
	if (calf == NULL) {
		ERRM("could not read calendar at `%s`\n", calpath);

		if (calpath_alloced)
			free(calpath);

		exit(EXIT_FAILURE);
	}

	if (calpath_alloced)
		free(calpath);

	cal = calendar_parse(calf);

	fclose(calf);

	if (cal.err_flag)
		exit(EXIT_FAILURE);

	/* output commands */
	if (cmd == OPT_COMMAND_CONSOLE)
		print_console(&cal);
	else
		print_script(&cal);

	calendar_wipe(&cal);
	
	return 0;
}