#include "opt.h" #include "err.h" #include "calendar.h" #include "print.h" #include "../reqs/simple-xdg-bdirs/simple-xdg-bdirs.h" #include #include #include #include #include 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 (INT_MAX < 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; }