diff options
Diffstat (limited to 'src/main.c')
-rw-r--r-- | src/main.c | 111 |
1 files changed, 77 insertions, 34 deletions
@@ -1,65 +1,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 every_opt_outputmode omode; - FILE *calendar; + enum every_opt_command cmd; + + char *calpath; + FILE *cal; - char **rdirs, **cur, *s; + char *ed; + pid_t pid; + int wstatus; + + char **rdirs, **cur; + bool calpath_alloced = false; opt_parse(argc, argv); - omode = opt_outputmode(); + cmd = opt_command(); if (opt_calpath() != NULL) { - s = opt_calpath(); - - calendar = fopen(s, "r"); - if (calendar == NULL) { - printf("err: could not read calendar at `%s`\n", s); - exit(EXIT_FAILURE); - } + calpath = opt_calpath(); } else { rdirs = simple_xdg_bdirs_read_dirs(SIMPLE_XDG_BDIRS_CONFIG); - if (rdirs == NULL) { - printf( - "err: no calendar specified, and default was not found or " - "readable\n" - ); - exit(EXIT_FAILURE); - } + if (rdirs == NULL) + ERR("no calendar specified, and default was not found or readable"); - s = simple_xdg_bdirs_fullpath_read("every/calendar", rdirs); + calpath = simple_xdg_bdirs_fullpath_read("every/calendar", rdirs); for (cur = rdirs; *cur != NULL; cur++) free(*cur); free(rdirs); - if (s == NULL) { - printf( - "err: no calendar specified, and default was not found or " - "readable\n" - ); - exit(EXIT_FAILURE); + 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"); } - calendar = fopen(s, "r"); + 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); - free(s); + ERR("editor failed to spawn"); + } else { + if (waitpid(pid, &wstatus, 0) == -1) { + if (calpath_alloced) + free(calpath); - if (calendar == NULL) { - printf( - "err: no calendar specified, and default was not found or " - "readable\n" - ); - exit(EXIT_FAILURE); + 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); } - fclose(calendar); + /* 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; } |