├── .gitignore
├── src
├── data
│ ├── dline_icon.png
│ ├── defaults.json
│ └── luc.b64
├── api
│ ├── gca.sh
│ └── oha.sh
└── utils
│ ├── _model.sh
│ ├── _view.sh
│ └── _controller.sh
├── README.md
├── dline
└── LICENSE
/.gitignore:
--------------------------------------------------------------------------------
1 | .dlinerc
2 | *settings.json
3 | *.tsv
4 | *.txt
5 | tmp*
6 |
--------------------------------------------------------------------------------
/src/data/dline_icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/jazz-it/dline/HEAD/src/data/dline_icon.png
--------------------------------------------------------------------------------
/src/data/defaults.json:
--------------------------------------------------------------------------------
1 | {
2 | "categories": {
3 | "0": {"name": "Resolved", "color": "color_resolved", "bullet": "bullet_resolved", "range": 0, "show": 1},
4 | "1": {"name": "Deadline", "color": "color_deadline", "bullet": "bullet_deadline", "range": 0, "show": 1},
5 | "2": {"name": "Work", "color": "color_work", "bullet": "bullet_work", "range": 1, "show": 1},
6 | "3": {"name": "Personal", "color": "color_personal", "bullet": "bullet_personal", "range": 1, "show": 1},
7 | "4": {"name": "Birthday & Anniversary", "color": "color_birthday", "bullet": "bullet_birthday", "range": 0, "show": 1},
8 | "5": {"name": "Public Holiday", "color": "color_public_holiday", "bullet": "bullet_public_holiday", "range": 1, "show": 1},
9 | "6": {"name": "Vacation", "color": "color_vacation", "bullet": "bullet_vacation", "range": 1, "show": 1},
10 | "7": {"name": "Sick Leave", "color": "color_sick_leave", "bullet": "bullet_sick_leave", "range": 1, "show": 1},
11 | "8": {"name": "School Holiday", "color": "color_school_holiday", "bullet": "bullet_school", "range": 1, "show": 1}
12 | },
13 | "reminders": [],
14 | "verbose": 1,
15 | "legend": 1,
16 | "school": 0,
17 | "scheduled_cleanup": 0,
18 | "oha_imported": "",
19 | "oha_country_iso": "",
20 | "oha_language_iso": "",
21 | "oha_subdivision_iso": "",
22 | "gca_skip": 0,
23 | "gca": [],
24 | "process_overdues": 0,
25 | "active_file": ""
26 | }
27 |
--------------------------------------------------------------------------------
/src/data/luc.b64:
--------------------------------------------------------------------------------
1 | Li4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi5fX19fX19fXy4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLgouLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4sLi3igJjigJ0uLi4uLi4uLi4uLi4uLi4uLi4uYGB+LiwuLi4uLi4uLi4uLi4uLi4uLi4KLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4sLi3igJ0uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLuKAnC0uLC4uLi4uLi4uLi4uLgouLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLC8uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLuKAnTosLi4uLi4uLi4KLi4uLi4uLi4uLi4uLi4uLi4uLi4uLD8uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi5cLC4uLi4uCi4uLi4uLi4uLi4uLi4uLi4uLi4vLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4sfS4uLi4KLi4uLi4uLi4uLi4uLi4uLi4vLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLDpgXmAuLn0uLi4uCi4uLi4uLi4uLi4uLi4uLi8uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4sOuKAnS4uLi4uLi4uLi8uLi4uLgouLi4uLi4uLi4uLi4uLj8uLi4uLl9fLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi46YC4uLi4uLi4uLi4uLy4uLi4uCi4uLi4uLi4uLi4uLi4vX18uKC4uLi4u4oCcfi0sXy4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLiw6YC4uLi4uLi4uLi4vLi4uLi4uLi4KLi4uLi4uLi4uLi4vKF8uLi4u4oCdfixfLi4uLi4uLi7igJx+LF8uLi4uLi4uLi4uLi4uLi4uLi4uLiw6YC4uLi4uLi4uXy8uLi4uLi4uLi4uLgouLi4uLi4uLi4uey4uXyQ7Xy4uLi4uLuKAnT0sXy4uLi4uLi7igJwtLF8uLi4uLi4uLC4tfi0sfSwufuKAnTsvLi4uLn0uLi4uLi4uLi4uLgouLi4uLi4uLi4uLigoLi4uLi4qfl8uLi4uLi4u4oCdPS0uXy4uLi4uLuKAnDssLC4vYC4uLi4v4oCdLi4uLi4uLi4uLi4uLi4vLi4uLi4uLi4uLi4uCi4uLiwsLF9fXy5cYH4sLi4uLi4u4oCcfi4sLi4uLi4uLi4uLi4uLi4uLi4uLi5gLi4uLi59Li4uLi4uLi4uLi4uLi4vLi4uLi4uLi4uLi4uLgouLi4uLi4uLi4uLi4oLi4uLmA9LSwsLi4uLi4uLmAuLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4oLi4uLi4uO18sLC3igJ0uLi4uLi4uLi4uLi4uLi4KLi4uLi4uLi4uLi4uLy5gfiwuLi4uLi5gLS4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi5cLi4uLi4uL1wuLi4uLi4uLi4uLi4uLi4uLi4uCi4uLi4uLi4uLi4uLi5cYH4uKi0sLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLnwsLi8uLi4uLlwsX18uLi4uLi4uLi4uLgosLF8uLi4uLi4uLi4ufS4+LS5fXC4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4ufC4uLi4uLi4uLi4uLi4uYD1+LSwuLi4uCi4uLi4uYD1+LSxfXF8uLi4uLi5gXCwuLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi5cLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uCi4uLi4uLi4uLi4uLi4uLi4uLi5gPX4tLCwuXCwuLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uXC4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uCi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uYDosLC4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLmBcLi4uLi4uLi4uLi4uLi5fXy4uCi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi5gPS0sLi4uLi4uLi4uLi4uLi4uLi4uLiwlYD4tLT09YGAuLi4uLi4uCi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi5fXC4uLi4uLi4uLi4uXywtJS4uLi4uLi5gXC4uLi4uLi4uLi4uLi4uLgouLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLi4uLiw8YC4uX3xfLC0mYGAuLi4uLi4uLi4uLi4uLi4uYFwuLi4uLi4uLi4uLi4uLgpKZWFuLUx1YyBqdXN0IGdhdmUgeW91IGEgZmFjZXBhbG0u
2 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 | # dLine
3 |
4 |
dLine is a simple and powerful command-line tool that brings your calendar directly to your terminal. You can track important dates, add events quickly using APIs, calculate timespans, and manage multiple calendars—all without leaving your terminal.
5 |
6 | Designed for developers, dLine makes managing your schedule smooth and efficient.
7 |
8 | ## Features
9 |
10 | 
11 |
12 | - Dynamic View:
13 | Run `dline` without arguments to see the current month’s events at a glance. Past dates are shaded, future events are highlighted, and color-coded categories make it easy to navigate. You can even filter out categories for a cleaner view.
14 |
15 | - Static View:
16 | Use `dline -m yyyy/mm` to display a simple monthly calendar for any given month. Great for when you just need a clear snapshot without additional details.
17 |
18 | - Event Calculator View:
19 | Need to count workdays between two dates? `dline -w start_date end_date` does it for you, categorizing weekdays and weekends automatically.
20 |
21 | - Administration:
22 | Easily manage your calendar datasets with `dline -b`. Add, delete, update, and clean your data as needed. Switching between multiple calendars or importing public holidays is simple. There's even a way to terminate all reminder processes.
23 |
24 | On the first launch, dLine will ask for your region to fetch relevant holidays. Don't worry — you can change this later if needed.
25 |
26 | ## Introduction on YouTube:
27 | [](https://www.youtube.com/shorts/aZMAY2oSTks)
28 |
29 | ## Screenshots
30 |
31 | Dynamic View
32 | 
33 |
34 | Static View
35 | 
36 |
37 | Event Calculator View
38 | 
39 |
40 | Admin
41 | 
42 |
43 | ## Documentation
44 |
45 | ```
46 | Usage:
47 | dline -a Add event (interactive mode)
48 | dline -a 2024/04/17 3 "11:30 Lunch with Lucy" Add event directly
49 | dline Show current month calendar
50 |
51 | Options:
52 | -a, --add [yyyy/mm/dd] [x] [desc] Add event. No args invokes interactive mode
53 | -b, --base Manage your data, as snapshots of your changes
54 | (file management)
55 | -c, --clean Remove old entries
56 | -d, --delete [GCA|OHA|pattern] Delete imported calendars, or local matching entries.
57 | -e, --export Export calendar to TSV format
58 | -f, --filter [x] [x] ... Toggle visibility of one or more categories
59 | -h, --help Show help
60 | -i, --import [TSV|GCA|OHA] Import events from external sources
61 | -k, --kill Terminate pending reminders
62 | -l, --legend Toggle legend display
63 | -m, --month [yyyy/mm] Show monthly calendar
64 | -o, --open Open data file in terminal editor
65 | -p, --print-details Toggle calendar details
66 | -r, --resolve Interactive dialogue to resolve deadlines
67 | -s, --school [0|1] Set school holidays as work days (0) or holidays (1)
68 | -t, --test [yyyy/mm/dd] Set "today" for testing
69 | -u, --update [GCA|OHA] | [pattern] [yyyy/mm/dd] [x] [desc] Update from APIs or local matching entries
70 | -v, --version Show version
71 | -w, --workdays [start_date] [end_date] Calculate workdays from optional start_date
72 | (default: today) to end_date
73 | -x, --xdg-open Open data file in GUI editor
74 |
75 | Event categories [x]:
76 | 1: Deadline
77 | 2: Work
78 | 3: Personal
79 | 4: Birthday & Anniversary
80 | 5: Public Holiday
81 | 6: Vacation
82 | 7: Sick Leave
83 | 8: School Holiday
84 | ```
85 |
86 | ### Default View:
87 |
88 | 1. Automated Processes:
89 | - The Dynamic View operates autonomously, continuously monitoring your calendar data.
90 | - It doesn’t require explicit user input; hence, the name “Dynamic.”
91 | 2. Countdown to Deadlines:
92 | - The background processes diligently search for the most relevant deadlines.
93 | - It looks ahead into the foreseeable future, spanning up to 6 months or until the end of the current year (whichever is further), scanning for unresolved deadlines.
94 | - Additionally, it scans the relevant past, reaching up to 1 month ago, searching for overdue deadlines.
95 | - The goal? To present you with a countdown to the nearest most important unresolved event.
96 | 3. Foreseeable Events:
97 | - Beyond deadlines, the Dynamic View also identifies other crucial events.
98 | - It anticipates events that require your attention within a specific timeframe—up to 48 hours ahead.
99 | - If such events exist, it creates a time trigger for pop-up notifications.
100 | - Even if you restart your PC, these countdowns persist, thanks to the `at` command.
101 | 4. Maintenance and Updates:
102 | - The Dynamic View handles routine maintenance tasks.
103 | - Cleanups: Removing outdated or irrelevant data.
104 | 5. Automatic Updates: Fetching fresh calendar events from APIs.
105 | - You can configure the timing and frequency of these processes through the `.dlinerc` file.
106 | - User translations and custom color schemes are also supported, ensuring a personalized experience.
107 |
108 | In summary, the Dynamic View is your new default, proactive calendar companion, silently managing deadlines, events, and data hygiene.
109 |
110 | #### Categories Filtration:
111 | Use `dline -f` and input the category codes you wish to view or hide (e.g. `dline -f 4 6 8`). This feature simplifies your calendar, allowing you to focus on the categories that matter most to you at any given time.
112 |
113 | #### Config Files:
114 |
115 | - `.dlinerc`: system-wide settings like user translations, color themes, cleanup frequencies
116 | - `settings.json`: calendar-specific preferences
117 |
118 | #### Data File:
119 |
120 | - `events_data.txt`: Default data file, but upon creation of a new calendar, a file with a prefix is added. It's possible to switch between the existing calendars by `dline -b` > `Select`.
121 |
122 |
123 | ## Installation
124 |
125 | #### Required Dependencies:
126 | Before the first run, make sure you have:
127 |
128 | ```
129 | https://salsa.debian.org/debian/at
130 | https://github.com/jqlang/jq
131 | ```
132 |
133 | #### Optional Dependencies (recommended):
134 |
135 | ```
136 | https://github.com/insanum/gcalcli
137 | https://github.com/junegunn/fzf
138 | https://github.com/pyrho/hack-font-ligature-nerd-font
139 | ```
140 | With the right setup, dLine could integrate with your Google Calendar. By aligning your calendar categories with dLine's system, you can import events directly, making your schedule accessible locally or via Google Calendar, according to your preference. [Important resolution of a relevant issue](https://github.com/insanum/gcalcli/issues/674#issuecomment-1890388400).
141 |
142 | ### Credits:
143 |
144 | Holiday data based on [OpenHolidays API](https://www.openholidaysapi.org/)
145 |
146 |
147 | ### Minimum Requirements:
148 |
149 | Bash Version: dLine requires Bash 4.0 or newer. Older versions (e.g., Bash 3.x on macOS) will not work correctly due to unsupported features like associative arrays.
150 |
151 | - To update Bash on macOS: Use Homebrew (`brew install bash`).
152 |
153 |
154 | ### Holiday Data and Google Calendar Integration:
155 |
156 | If OpenHolidaysAPI doesn't support your country, you can still integrate holidays by:
157 |
158 | 1. Creating a [separate Google Calendar for public holidays](https://support.google.com/calendar/answer/13748345) in your region.
159 |
160 | 2. Running `dline --import GCA` to sync it with dLine.
161 |
162 | 3. Assigning the imported events to the “Public Holiday” category during the setup prompt.
163 |
164 | This process works for School Holidays and other custom calendars too!
165 |
166 |
167 | ### Filtering Events with fzf
168 |
169 | When using `dline -b`, select "View" and choose a dataset. If `fzf` is installed, it will be triggered, allowing you to filter entries interactively. For example, you can filter all meetings in June this year labeled with #projectX easily using this feature.
170 |
171 |
172 | ## Usage/Examples
173 |
174 | ```bash
175 | dline -a 2024/07/04 3 Buy milk
176 | ```
177 | - Adding a new event (`yyyy/mm/dd x desc`), where `x` is the category code, `desc` is an arbitrary description with a special case where the description may start with `hh:mm` time format (which will eventually trigger a scheduled reminder as a popup) and may end with any hashtag (e.g. `#projectX`) for easier event handling related to a single topic.
178 |
179 |
180 | ```bash
181 | dline -d "#projectX"
182 | ```
183 | - Deleting all events tagged with `#projectX`.
184 |
185 |
186 | ```bash
187 | dline -f 4 6 8
188 | ```
189 | - Toggling visibility of events with codes 4 (Birthday & Anniversary), 6 (Vacation) and 8 (School Holiday).
190 |
191 |
192 | ```bash
193 | dline -i GCA
194 | ```
195 | - Triggers an import of calendar(s) from Google Calendar in interractive mode. Read the docs from the project `gcalcli` first. The same operation will be triggered during the very first run, so you may want to run it again if you need to import a new calendar.
196 |
197 |
198 | ```bash
199 | dline -s 1
200 | ```
201 | - In case you're a student, run this to make sure your School Holidays are shown as days off, not as work days.
202 |
203 |
204 | ```bash
205 | dline -s 0
206 | ```
207 | - If you’re a parent, use this command to view School Holidays in your region as regular work days. It serves as a reminder to stay informed about when your kids will be off from school.
208 |
209 |
210 | ```bash
211 | dline -m 2024/10
212 | ```
213 | - Displaying a static monthly calendar, without triggering any automatic background process.
214 |
215 |
216 | ```bash
217 | dline -w 2024/01/01 2024/12/31
218 | ```
219 | - Once you’ve added all your calendars to dLine, you can utilize the command above to assess a specific timespan. It helps you determine the number of distinct event categories within your specified time range. This feature proves especially useful for freelancers who charge based on workdays—allowing them to calculate holidays, sick days, weekends, and workdays before providing quotes to their clients.
220 |
221 | ## Appendix
222 |
223 | Managing time effectively is key to productivity. dLine simplifies scheduling, so you can focus on what matters most.
224 |
225 | ## Easter Egg Alert
226 | Attention devs! There's a hidden Easter Egg in this project. If you find it, let us know and get featured in our "Hall of Fame". Happy coding! 🚀
227 |
228 | ## Hall of Fame
229 | [James Cuzella (@trinitronx)](https://github.com/trinitronx)
230 |
--------------------------------------------------------------------------------
/src/api/gca.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # Specify your date range
4 | _gca_start_date=${TODAY////-}
5 | _gca_end_date="${next_year}-12-31"
6 | today=${_gca_start_date}
7 | # Create temporary files
8 | tempfile=$(mktemp)
9 | temp_output=$(mktemp)
10 |
11 |
12 | # Delete selected entries
13 | delete_gca_lines() {
14 | awk -v start_date="$1" -v end_date="$2" -v code="$3" '
15 | BEGIN { FS = OFS = " " }
16 | $1 ~ /^[0-9]{4}\/[0-9]{2}\/[0-9]{2}$/ && $1 >= start_date && $1 <= end_date {
17 | if (code != "") {
18 | if ($2 == code && $0 ~ / #gc$/) {
19 | next; # Skip this line
20 | }
21 | }
22 | }
23 | { print } # Print all other lines
24 | ' "${INPUT_FILE}" >| ${tempfile}
25 | if [[ -s ${tempfile} ]]; then
26 | mv ${tempfile} ${INPUT_FILE}
27 | else
28 | rm ${tempfile}
29 | fi
30 | }
31 |
32 |
33 | # Delete the entry from the $SETTINGS
34 | delete_gca_json() {
35 | echo "Please select an imported Google Calendar to delete:"
36 | for ((i=0; i<${num_gca}; i++)); do
37 | j=$((i+1))
38 | if [[ -n ${defaults["gca[$i][name]"]} ]]; then
39 | echo -e " [${yellow}${j}${reset}] ${defaults["gca[$i][name]"]}"
40 | else
41 | echo -e " [${yellow}${j}${reset}] Multiple calendars"
42 | fi
43 | done
44 | [[ $j -ne 1 ]] && echo -e " [${yellow}A${reset}] All calendars from above"
45 | echo -e " [${yellow}X${reset}] Cancel"
46 | echo
47 |
48 | # Infinite loop until a valid option is chosen
49 | while true; do
50 | read -p "Enter a calendar code: " choice
51 |
52 | # Check if the choice is a valid calendar "key"
53 | if [[ ( "${choice}" =~ ^[1-9][0-9]*$ && ${choice} -le ${j} && ${choice} -gt 0 ) || ${choice^^} == "A" || ${choice^^} == "X" ]]; then
54 | if [[ ${choice^^} == "A" ]]; then
55 | selected_cal="All calendars"
56 | elif [[ ${choice^^} == "X" ]]; then
57 | echo "Operation cancelled"
58 | echo
59 | return
60 | elif [[ -n ${defaults["gca[$((choice-1))][name]"]} && ${choice} -le ${j} ]]; then
61 | selected_cal="${defaults["gca[$((choice-1))][name]"]}"
62 | else
63 | selected_cal="Multiple calendars"
64 | fi
65 | echo "▸▸▸ Selected: ${selected_cal}"
66 | echo
67 | if [[ ${choice^^} == "A" ]]; then
68 | if delete_line " #gc$"; then
69 | jq 'del(.gca[] | select(.name != ""))' ${SETTINGS} > temp.json && mv temp.json ${SETTINGS}
70 | fi
71 | break
72 | elif [[ ${selected_cal} == "Multiple calendars" ]]; then
73 | delete_gca_lines ${defaults["gca[$((choice-1))][imported_date]"]} ${defaults["gca[$((choice-1))][end_date]"]} ${defaults["gca[$((choice-1))][category]"]}
74 | # Delete the entry from the JSON file
75 | jq --arg name "${defaults["gca[$((choice-1))][name]"]}" 'del(.gca[] | select(.name == $name))' ${SETTINGS} > temp.json && mv temp.json ${SETTINGS}
76 | else
77 | delete_gca_lines ${defaults["gca[$((choice-1))][imported_date]"]} ${defaults["gca[$((choice-1))][end_date]"]}
78 | # Delete the entry from the JSON file
79 | jq 'del(.gca[] | select(.name != ""))' ${SETTINGS} > temp.json && mv temp.json ${SETTINGS}
80 | fi
81 | echo -e "${yellow}${selected_cal}${reset} deleted successfully."
82 | sort_input
83 | echo
84 | break
85 | else
86 | echo "Invalid choice. Please enter a valid option."
87 | echo
88 | fi
89 | done
90 | }
91 |
92 |
93 | # Update the entry from the $SETTINGS
94 | update_gca_json() {
95 | # If no existing entry is found, append the new entry to the reminders attribute in the $SETTINGS file
96 | jq --arg name "${calendar_name}" --arg imported_date "${today}" --arg end_date "${_gca_end_date}" --arg category "${selected_code}" '
97 | if (.gca | map(select(.name == $name)) | length > 0)
98 | then
99 | .gca |= map(if .name == $name then . + {imported_date: $imported_date, end_date: $_gca_end_date, category: $category} else . end)
100 | else
101 | .gca += [{name: $name, imported_date: $imported_date, end_date: $_gca_end_date, category: $category}]
102 | end
103 | ' "${SETTINGS}" > temp.json && mv temp.json "${SETTINGS}"
104 | }
105 |
106 |
107 | # Import Google Calendar
108 | import_gca() {
109 | if [[ -n $1 && -z $2 ]]; then
110 | arg_choice="A"
111 | selected_code="${1}"
112 | selectAll=1
113 | elif [[ ${#1} -eq 1 && -n $2 ]]; then
114 | selected_code="${1}"
115 | shift
116 | selected_calendar="$@"
117 | fi
118 |
119 | selectAll=0
120 | # Convert the variable into an array (one option per line)
121 | IFS=$'\n' read -d '' -ra calendar_array <<< "$calendars"
122 | # IFS=$'\n' read -d '' -ra calendar_array <<< "$(echo "$calendars" | awk 'NF {print substr($0, index($0, $3))}')"
123 |
124 | if [[ -z ${selected_calendar} && -z ${selected_code} ]]; then
125 | # Calculate the max number of iterations
126 | remaining_gca=$(( ${num_lines} - ${num_gca} ))
127 | [[ $remaining_gca -lt 1 ]] && remaining_gca=1
128 | for (( remaining=0; remaining<${remaining_gca}; remaining++ )); do
129 | # Display the menu
130 | echo "Please select a Google Calendar to import:"
131 | for i in "${!calendar_array[@]}"; do
132 | if [[ -n ${calendar_array[i]} && ! "${calendar_array[i]}" =~ ^[[:space:]]*$ ]]; then
133 | echo -e " [${yellow}$((i+1))${reset}] ${calendar_array[i]}"
134 | fi
135 | done
136 | [[ $i -ne 0 ]] && echo -e " [${yellow}A${reset}] All calendars above"
137 | echo -e " [${yellow}X${reset}] Don't ask me again"
138 | echo
139 |
140 | # Infinite loop until a valid option is chosen
141 | while true; do
142 | read -p "Select an option: " choice
143 |
144 | # Check if the choice is a valid integer or "x"
145 | if [[ "$choice" =~ ^[1-9][0-9]*$ && "$choice" -le "${#calendar_array[@]}" || "${choice^^}" == "A" || "${choice^^}" == "X" ]]; then
146 | if [ "${choice^^}" == "X" ]; then
147 | jq --argjson gca_skip 1 '.gca_skip = $gca_skip' $SETTINGS > tmp.$$.json && mv tmp.$$.json $SETTINGS && echo "▸▸▸ Selected: Don't ask me again"
148 | echo
149 | return
150 | elif [ "${choice^^}" == "A" ]; then
151 | selectAll=1
152 | remaining=${remaining_gca} # Prevent importing more calendars
153 | echo "▸▸▸ Selected: All calendars"
154 | echo
155 | break
156 | else
157 | selected_calendar="${calendar_array[choice-1]}"
158 | echo "▸▸▸ Selected: ${selected_calendar}"
159 | echo
160 | break
161 | fi
162 | else
163 | echo "Invalid choice. Please enter a valid option."
164 | echo
165 | fi
166 | done
167 |
168 | echo "Select a corresponding category:"
169 | jq -r '.categories | to_entries[] | select(.key != "0") | "\(.key)\t\(.value.name)"' ${SETTINGS} | awk -v yellow="${yellow}" -v reset="${reset}" 'BEGIN{FS="\t"}{printf " [%s%s%s] %s\n", yellow, $1, reset, $2}'
170 | echo
171 |
172 | # Infinite loop until a valid option is chosen
173 | while true; do
174 | read -p "Enter a category code: " choice
175 |
176 | # Check if the choice is a valid category "key"
177 | if [[ -z ${defaults["categories[${choice}][name]"]} ]]; then
178 | echo "Invalid choice. Please enter a valid option."
179 | echo
180 | else
181 | selected_code="${choice}"
182 | echo "▸▸▸ Selected: ${defaults["categories[${choice}][name]"]}"
183 | echo
184 | break
185 | fi
186 | done
187 |
188 | yes_no "Import another Google Calendar?"
189 | if [[ $user_input == "yes" ]] ; then
190 | echo
191 | else
192 | break
193 | fi
194 | done
195 | fi
196 |
197 | # Get the events from gcalcli
198 | if [[ ${selectAll} -ne 1 ]]; then
199 | events=$(gcalcli --calendar "${selected_calendar}" agenda --tsv "${_gca_start_date}" "${_gca_end_date}" | awk '{print $1, $2, substr($0, index($0, $5))}')
200 | else
201 | events=$(gcalcli agenda --tsv "${_gca_start_date}" "${_gca_end_date}" | awk '{print $1, $2, substr($0, index($0, $5))}')
202 | fi
203 |
204 | # Process each line of the events
205 | echo "$events" | while read -r line; do
206 | # Extract the date, time, and summary from the line
207 | date=$(echo $line | awk '{print $1}')
208 | time=$(echo $line | awk '{print $2}')
209 | summary=$(echo $line | cut -d' ' -f3-)
210 |
211 | # If the date is not in the correct format, use the previous date
212 | if [[ ! $date =~ ^[0-9]{4}\-[0-1]{1}[0-9]{1}\-[0-3]{1}[0-9]{1}$ || $date < $today ]]; then
213 | continue
214 | else
215 | date=${date//-//}
216 | fi
217 |
218 | # Detect birthdays, name days and anniversaries
219 | shopt -s nocasematch
220 | if [[ $summary =~ (birthday|name day|anniversary)$ ]]; then
221 | code=4
222 | else
223 | code=$selected_code
224 | fi
225 | shopt -u nocasematch
226 |
227 | # Print the formatted event
228 | if [[ $time == "00:00" ]]; then
229 | echo "$date $code $summary #gc"
230 | else
231 | echo "$date $code $time $summary #gc"
232 | fi
233 | done >| ${tempfile}
234 |
235 | # Loop through each line in the tempfile
236 | while IFS= read -r line; do
237 | # Extract the date and message, excluding the single digit code
238 | leading=$(echo "$line" | awk '{print substr($0, 1, 11)}')
239 | trailing=$(echo "$line" | awk '{print substr($0, 13)}')
240 |
241 | # Sensible cherry picking the insertion of the new events:
242 | # Check if the same event exists in the input file with any category key
243 | if ! grep "^${leading}[[:alnum:]]${trailing}$" "$INPUT_FILE" > /dev/null; then
244 | # Only if the event does not exist, append the line to the temporary output file
245 | echo "$line" >> "$temp_output"
246 | fi
247 | done < "${tempfile}"
248 |
249 | # Check if temp_output has at least one non-empty line
250 | if [ $(grep -c . "$temp_output") -gt 0 ]; then
251 | # Append the non-empty lines from temp_output to the input file
252 | grep . "$temp_output" >> "$INPUT_FILE"
253 | if [[ ${selectAll} -ne 1 ]]; then
254 | calendar_name="${selected_calendar}"
255 | update_gca_json
256 | else
257 | # All calendars are inserted under the same category
258 | for i in "${!calendar_array[@]}"; do
259 | if [[ -n ${calendar_array[$i]} && ! "${calendar_array[$i]}" =~ ^[[:space:]]*$ ]]; then
260 | calendar_name="${calendar_array[$i]}"
261 | update_gca_json
262 | fi
263 | done
264 | fi
265 | fi
266 |
267 | # Remove the temporary output file
268 | rm "$tempfile"
269 | rm "$temp_output"
270 | }
271 |
272 | gca() {
273 | # Get all calendars from gcalcli list and strip all ANSI sequences from it
274 | calendars=$(gcalcli list 2>/dev/null | awk 'NR>2 && NF {print substr($0, index($0, $3))}' | sed -E 's/\x1B\[[0-9;]*[a-zA-Z]//g')
275 | num_lines=$(echo "$calendars" | wc -l)
276 |
277 | # iterate through all end_dates and update the existing calendars only if needed
278 | # enable a flag for updating calendars
279 | # enable a flag for deleting calendars
280 | # remove the Multiple calendars option and save individual entries instead
281 |
282 | # Check if the calendars variable is not empty
283 | if [[ -n "$calendars" ]]; then
284 | if [[ -z "$@" ]]; then
285 | import_gca
286 | else
287 | import_gca "$@"
288 | fi
289 | fi
290 | }
291 |
292 |
293 | # Iterate through all outdated imported calendars and run auto update
294 | gca_auto_update() {
295 | for (( i=0; i<${#outdated_names[@]}; i++ )); do
296 | j=${outdated_index[$i]}
297 | gca "${defaults["gca[$j][category]"]}" "${defaults["gca[$j][name]"]}"
298 | done
299 | }
300 |
--------------------------------------------------------------------------------
/src/api/oha.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Define the URLs
4 | URL_countries="https://openholidaysapi.org/Countries"
5 | URL_languages="https://openholidaysapi.org/Languages"
6 | URL_subdivisions="https://openholidaysapi.org/Subdivisions?countryIsoCode=" # ${key}
7 |
8 | # Define the temporary files and the refresh period
9 | TMP_FILE_COUNTRIES="/tmp/dline_OHA_countries.json"
10 | TMP_FILE_LANGUAGES="/tmp/dline_OHA_languages.json"
11 | REFRESH_PERIOD=$((60*60*24*30*12)) # 12 months in seconds
12 |
13 |
14 | delete_oha() {
15 | # Delete all instances of imported entries from OpenHolidaysAPI
16 | if delete_line " #oh$"; then
17 | # Reset 'oha_imported' from the $LOGS_FILE
18 | current_date_dd=""
19 | update_api_date_log
20 | # Reset 'oha_country_iso' from the $LOGS_FILE
21 | key=""
22 | update_oha_country_log
23 | # Reset 'oha_language_iso' from the $LOGS_FILE
24 | language_key=""
25 | update_oha_language_log
26 | # Reset 'oha_subdivision_iso' from the $LOGS_FILE
27 | subdivision_isoCode=""
28 | update_oha_subdivision_log
29 | fi
30 | }
31 |
32 |
33 | input_language() {
34 | # Get the available languages for the selected key from the countries data
35 | official_languages=$(echo "$content_countries" | jq -r --arg key "$key" '.[] | select(.isoCode==$key) | .officialLanguages[]')
36 |
37 | # Initialize an array to store the language options
38 | language_options=()
39 |
40 | # Add English as the first option
41 | language_options+=("EN English")
42 |
43 | # Loop through the official languages
44 | for language_key in $official_languages; do
45 | # Skip if the language key is EN since we already added English
46 | if [ "$language_key" != "EN" ]; then
47 | # Get the English name of the language from the languages data
48 | language_name=$(echo "$content_languages" | jq -r --arg key "$language_key" '.[] | select(.isoCode==$key) | .name[] | select(.language=="EN") | .text')
49 |
50 | # Add the language option to the array
51 | language_options+=("${language_key} ${language_name}")
52 | fi
53 | done
54 |
55 | # Print the available languages with formatting and a tab separator
56 | echo "Available Languages:"
57 | for line in "${language_options[@]}"; do
58 | language_key=$(echo "${line}" | cut -d' ' -f1)
59 | language_name=$(echo "${line}" | cut -d' ' -f2-)
60 | echo -e " [${yellow}${language_key}${reset}] ${language_name}"
61 | done
62 |
63 | # Initialize a variable to keep track of whether the user's selection is valid
64 | valid=false
65 | echo
66 |
67 | # Loop until the user's selection is valid
68 | while [ "$valid" = false ]; do
69 | # Prompt the user to choose a language
70 | read -p "Please choose a language from the list above (enter the value in square brackets): " language_key
71 |
72 | # Convert the user's input to uppercase
73 | language_key=${language_key^^}
74 |
75 | # Validate the user's input
76 | for line in "${language_options[@]}"; do
77 | language_isoCode=$(echo "${line}" | cut -d' ' -f1)
78 | language_name=$(echo "${line}" | cut -d' ' -f2-)
79 | if [[ "${language_isoCode^^}" == "${language_key}" ]]; then
80 | echo "▸▸▸ Selected: ${language_name}"
81 | echo
82 | valid=true
83 | break
84 | fi
85 | done
86 |
87 | if [ "$valid" = false ]; then
88 | echo "Invalid selection. Please enter a language code from the list."
89 | echo
90 | fi
91 | done
92 | }
93 |
94 |
95 | input_country() {
96 | # Use jq to parse the JSON and print the key-name pairs
97 | keys=$(echo "${content_countries}" | jq -r '.[] | "\(.isoCode) \(.name[] | select(.language=="EN") .text)"')
98 |
99 | # Add an option for "Other" or "Not listed"
100 | keys+=$(echo -e "\nX Other (Not listed)")
101 |
102 | # Print the key-name pairs
103 | echo "Available countries:"
104 | while IFS= read -r line; do
105 | key=$(echo "${line}" | cut -d' ' -f1)
106 | name=$(echo "${line}" | cut -d' ' -f2-)
107 | echo -e " [${yellow}${key}${reset}]\t${name}"
108 | done <<< "$keys"
109 |
110 | # Initialize a variable to keep track of whether the user's selection is valid
111 | valid=false
112 | echo
113 |
114 | # Loop until the user's selection is valid
115 | while [ "$valid" = false ]; do
116 | # Prompt the user to choose a key
117 | read -p "Please choose a key from the list above: " key
118 | key=${key^^}
119 |
120 | # Validate the user's input
121 | while IFS= read -r line; do
122 | country_isoCode=$(echo "${line}" | cut -d' ' -f1)
123 | country_name=$(echo "${line}" | cut -d' ' -f2-)
124 | if [ "${key}" == "${country_isoCode^^}" ]; then
125 | echo "▸▸▸ Selected: ${country_name}"
126 | echo
127 | valid=true
128 | break
129 | fi
130 | done <<< "${keys}"
131 | if [ "$valid" = false ]; then
132 | echo "Invalid selection. Please enter a country code from the list."
133 | echo
134 | fi
135 |
136 | done
137 | }
138 |
139 | input_subdivisions() {
140 | # Define the URL for subdivisions
141 | URL_subdivisions+="${key}"
142 | TMP_FILE_SUBDIVISIONS="/tmp/dline_OHA_${key}_subdivisions.json"
143 |
144 | # Fetch the data for subdivisions
145 | fetch_data "$URL_subdivisions" "$TMP_FILE_SUBDIVISIONS"
146 |
147 | # Read the content from the temporary file
148 | content_subdivisions=$(cat "$TMP_FILE_SUBDIVISIONS")
149 |
150 | # Get the available subdivisions for the selected key
151 | subdivisions=$(echo "$content_subdivisions" | jq -r --arg lang "$language_key" '.[] | "\(.isoCode) \(.shortName) \(.name[] | select(.language==$lang) .text)"')
152 |
153 | # Check if there are any subdivisions
154 | if [ -n "$subdivisions" ]; then
155 | # Print the available subdivisions with formatting and a tab separator
156 | echo "Available Subdivisions:"
157 | while IFS= read -r line; do
158 | isoCodeSubdivision=$(echo "${line}" | cut -d' ' -f1)
159 | subdivision=$(echo "${line}" | cut -d' ' -f2)
160 | name=$(echo "${line}" | cut -d' ' -f3-)
161 | echo -e " [${yellow}${subdivision}${reset}]\t${name}"
162 | done <<< "${subdivisions}"
163 |
164 | # Initialize a variable to keep track of whether the user's selection is valid
165 | valid=false
166 | echo
167 |
168 | # Loop until the user's selection is valid
169 | while [ "$valid" = false ]; do
170 | # Prompt the user to choose a subdivision
171 | read -p "Please choose a subdivision from the list above: " subdivision
172 | subdivision=${subdivision^^}
173 |
174 | # Validate the user's input
175 | while IFS= read -r line; do
176 | subdivision_isoCode=$(echo "${line}" | cut -d' ' -f1)
177 | subdivision_shortName=$(echo "${line}" | cut -d' ' -f2)
178 | subdivision_name=$(echo "${line}" | cut -d' ' -f3-)
179 | if [ "${subdivision}" == "${subdivision_shortName^^}" ]; then
180 | echo "▸▸▸ Selected: ${subdivision_name}"
181 | echo
182 | valid=true
183 | break
184 | fi
185 | done <<< "${subdivisions}"
186 | if [ "$valid" = false ]; then
187 | echo "Invalid selection. Please enter a subdivision code from the list."
188 | echo
189 | fi
190 | done
191 | fi
192 | }
193 |
194 |
195 | export_public_holiday() {
196 | URL_public_holiday="https://openholidaysapi.org/PublicHolidays?countryIsoCode=${key}&languageIsoCode=${language_key}&validFrom=${current_year}-01-01&validTo=${next2_year}-12-31"
197 | TMP_FILE_PUBLIC_HOLIDAY="/tmp/dline_OHA_${key}_${language_key}_${current_year}_public_holiday.json"
198 |
199 | # Fetch the data for public holiday
200 | fetch_data "$URL_public_holiday" "$TMP_FILE_PUBLIC_HOLIDAY"
201 |
202 | # Read the content from the temporary file
203 | content_public_holiday=$(cat "$TMP_FILE_PUBLIC_HOLIDAY")
204 |
205 | # Get the public holidays for the selected country from the JSON data
206 | public_holidays=$(echo "$content_public_holiday" | jq -r --arg key "$key" --arg lang "$language_key" --arg sub "$subdivision" '.[] | select(.nationwide==true or (.subdivisions[]? | .shortName==$sub)) | "\(.startDate) \(.endDate) \(.name[] | select(.language==$lang) | .text)"')
207 |
208 | # Write the public holidays to a file
209 | while IFS= read -r line; do
210 | start_date=$(echo "$line" | cut -d' ' -f1)
211 | end_date=$(echo "$line" | cut -d' ' -f2)
212 | name=$(echo "$line" | cut -d' ' -f3-)
213 |
214 | # Skip invalid entries
215 | if [[ -z "$start_date" || -z "$end_date" || -z "$name" ]]; then
216 | continue
217 | fi
218 |
219 | # If the start date and end date are different, add multiple entries
220 | if [ "$start_date" != "$end_date" ]; then
221 | current_date="$start_date"
222 | while [ "$current_date" != "$end_date" ]; do
223 | # Check if the entry already exists in the file
224 | if ! grep -q "^${current_date//-//} 5 $name #oh$" $INPUT_FILE; then
225 | echo "${current_date//-//} 5 $name #oh" >> $INPUT_FILE
226 | fi
227 | current_date=$(date -I -d "$current_date + 1 day")
228 | done
229 | fi
230 |
231 | # Check if the entry already exists in the file
232 | if ! grep -q "^${end_date//-//} 5 $name #oh$" $INPUT_FILE; then
233 | echo "${end_date//-//} 5 $name #oh" >> $INPUT_FILE
234 | fi
235 | done <<< "$public_holidays"
236 | }
237 |
238 |
239 | export_school_holiday() {
240 | subdivision_isoCode="$(echo "${subdivision_isoCode}" | xargs)"
241 | if [[ -z "${subdivision_isoCode}" || "${subdivision_isoCode}" =~ ^0 ]]; then
242 | subdivision_isoCode="${oha_subdivision_iso}"
243 | fi
244 | language_isoCode="$(echo "${language_isoCode}" | xargs)"
245 | if [[ -z "${language_isoCode}" || "${language_isoCode}" =~ ^0 ]]; then
246 | language_isoCode="${oha_language_iso}"
247 | fi
248 |
249 | URL_school_holiday="https://openholidaysapi.org/SchoolHolidays?countryIsoCode=${key}&subdivisionCode=${subdivision_isoCode}&languageIsoCode=${language_isoCode}&validFrom=${current_year}-01-01&validTo=${next2_year}-12-31"
250 | TMP_FILE_SCHOOL_HOLIDAY="/tmp/dline_OHA_${key}_${subdivision_isoCode}_${language_isoCode}_${current_year}_school_holiday.json"
251 |
252 | # Fetch the data for school holiday
253 | fetch_data "$URL_school_holiday" "$TMP_FILE_SCHOOL_HOLIDAY"
254 |
255 | # Read the content from the temporary file
256 | content_school_holiday=$(cat "$TMP_FILE_SCHOOL_HOLIDAY")
257 |
258 | # Get the school holidays for the selected country from the JSON data
259 | school_holidays=$(echo "$content_school_holiday" | jq -r --arg key "$key" --arg lang "$language_key" --arg sub "$subdivision" '.[] | select(.nationwide==true or (.subdivisions[]? | .shortName==$sub)) | "\(.startDate) \(.endDate) \(.name[] | select(.language==$lang) | .text)"')
260 |
261 | # Write the school holidays to a file
262 | while IFS= read -r line; do
263 | start_date=$(echo "$line" | cut -d' ' -f1)
264 | end_date=$(echo "$line" | cut -d' ' -f2)
265 | name=$(echo "$line" | cut -d' ' -f3-)
266 |
267 | # Skip invalid entries
268 | if [[ -z "$start_date" || -z "$end_date" || -z "$name" ]]; then
269 | continue
270 | fi
271 |
272 | # If the start date and end date are different, add multiple entries
273 | if [ "$start_date" != "$end_date" ]; then
274 | current_date="$start_date"
275 | while [ "$current_date" != "$end_date" ]; do
276 | # Check if the entry already exists in the file
277 | if ! grep -q "^${current_date//-//} 8 $name #oh$" $INPUT_FILE; then
278 | echo "${current_date//-//} 8 $name #oh" >> $INPUT_FILE
279 | fi
280 | current_date=$(date -I -d "$current_date + 1 day")
281 | done
282 | fi
283 |
284 | # Check if the entry already exists in the file
285 | if ! grep -q "^${end_date//-//} 8 $name #oh$" $INPUT_FILE; then
286 | echo "${end_date//-//} 8 $name #oh" >> $INPUT_FILE
287 | fi
288 | done <<< "$school_holidays"
289 | }
290 |
291 |
292 | # Function to fetch data from a URL and save it to a temporary file
293 | fetch_data() {
294 | local url=${1}
295 | local tmp_file=${2}
296 |
297 | # Check if the temporary file exists and is not older than the refresh period
298 | if [[ ! -f "${tmp_file}" || $(($(date +%s) - $(date +%s -r "${tmp_file}"))) -gt $REFRESH_PERIOD ]]; then
299 | # Use curl to get the content from the URL and save it to the temporary file
300 | curl -s "${url}" -H "accept: text/json" >| "${tmp_file}"
301 | fi
302 | }
303 |
304 |
305 | update_api_date_log() {
306 | jq --arg current_date_dd "$current_date_dd" '.oha_imported = $current_date_dd' $SETTINGS > tmp.$$.json && mv tmp.$$.json $SETTINGS
307 | }
308 |
309 |
310 | update_oha_country_log() {
311 | jq --arg country_iso "$key" '.oha_country_iso = $country_iso' $SETTINGS > tmp.$$.json && mv tmp.$$.json $SETTINGS
312 | }
313 |
314 |
315 | update_oha_language_log() {
316 | jq --arg language_iso "$language_key" '.oha_language_iso = $language_iso' $SETTINGS > tmp.$$.json && mv tmp.$$.json $SETTINGS
317 | }
318 |
319 |
320 | update_oha_subdivision_log() {
321 | jq --arg subdivision_iso "$subdivision_isoCode" '.oha_subdivision_iso = $subdivision_iso' $SETTINGS > tmp.$$.json && mv tmp.$$.json $SETTINGS
322 | }
323 |
324 |
325 | oha() {
326 | # Fetch the data
327 | fetch_data "${URL_countries}" "${TMP_FILE_COUNTRIES}"
328 | fetch_data "${URL_languages}" "${TMP_FILE_LANGUAGES}"
329 |
330 | # Read the content from the temporary files
331 | content_countries=$(cat "$TMP_FILE_COUNTRIES")
332 | content_languages=$(cat "$TMP_FILE_LANGUAGES")
333 |
334 | oha_country_iso="$(echo "${oha_country_iso}" | xargs)"
335 | if [[ -z "${oha_country_iso}" || "${oha_country_iso}" =~ ^0 || "${1^^}" == "IMPORT" ]]; then
336 | input_country
337 | update_oha_country_log
338 | else
339 | key=$oha_country_iso
340 | fi
341 | if [[ ${key^^} == "X" ]]; then
342 | return 0
343 | fi
344 | oha_language_iso="$(echo "${oha_language_iso}" | xargs)"
345 | if [[ -z "${oha_language_iso}" || "${oha_language_iso}" =~ ^0 || "${1^^}" == "IMPORT" ]]; then
346 | input_language
347 | update_oha_language_log
348 | else
349 | language_key=$oha_language_iso
350 | fi
351 | oha_subdivision_iso="$(echo "${oha_subdivision_iso}" | xargs)"
352 | if [[ -z "${oha_subdivision_iso}" || "${oha_subdivision_iso}" =~ ^0 || "${1^^}" == "IMPORT" ]]; then
353 | input_subdivisions
354 | update_oha_subdivision_log
355 | else
356 | subdivision_isoCode=$oha_subdivision_iso
357 | fi
358 | export_public_holiday
359 | if [[ -z $@ ]]; then
360 | yes_no "Download school holidays for your region?"
361 | else
362 | yes_no "Download updates on school holidays for your region?"
363 | fi
364 | if [[ $user_input == "yes" ]]; then
365 | export_school_holiday
366 | fi
367 | echo "OpenHolidaysAPI: Operation completed."
368 | echo
369 | }
370 |
--------------------------------------------------------------------------------
/dline:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | declare -A MSG
3 | declare -A defaults
4 | declare -A report_workday
5 | declare -A report_weekend
6 |
7 | # NOTE: Configuration settings
8 | # If you would like to translate the output to your own language
9 | # copy/paste the content below into the new file called `.dlinerc`
10 | # and place it into the same directory with this script.
11 | # The file will be ignored from git, so you could freely edit all the values
12 | # from the associative array $MSG within the `.dlinerc` file which will override
13 | # all the default values below.
14 |
15 | MSG['progress']="Progress"
16 | MSG['day']="Day"
17 | MSG['week']="Week"
18 | MSG['today']="Today"
19 | MSG['time']="Time"
20 | MSG['day_singular']="day"
21 | MSG['day_plural']="days"
22 |
23 | MSG['days_until_the']="days until the"
24 | MSG['until_the']="until the"
25 | MSG['new_year']="New Year"
26 |
27 | MSG['workdays_left']="workdays left"
28 | MSG['days_until_deadline']="days until deadline"
29 | MSG['until_deadline']="until deadline"
30 | MSG['happy_new_year']="We made it! ☃️"
31 | MSG['soon']="Hurry up! 😊"
32 | MSG['overdue']="Time overdue (in days)"
33 |
34 | MSG['date_format']="YYYY/MM/DD"
35 | MSG['default_desc']="11:30 Lunch with Lucy"
36 | MSG['new_date']="New event date"
37 | MSG['new_date_zsh']="New event date [%B%F{yellow}${MSG['date_format']}%f]: "
38 | MSG['new_desc']="Event description"
39 | MSG['new_desc_zsh']="Event description [%B%F{yellow}${MSG['default_desc']}%f]: "
40 | MSG['start_date']="Start date"
41 | MSG['start_date_zsh']="Start date [%B%F{yellow}${MSG['date_format']}%f]: "
42 | MSG['end_date']="End date"
43 | MSG['end_date_zsh']="End date [%B%F{yellow}${MSG['date_format']}%f]: "
44 |
45 | # Color configuration could be also altered within .dlinerc
46 | alert="\033[38;5;167m" # Orange
47 | effect_blink="\033[5m" # Blinking text
48 | effect_crossed_out="\033[9m" # Crossed-out text
49 | color_header="\033[38;5;109m" # Bright Blue
50 | color_past_dates="\033[38;5;67m" # Dark Cyan
51 | color_past_months="\033[38;5;109m" # Bright Blue
52 | color_today="\033[38;5;233;48;5;67m" # Dark Cyan background with Black text
53 | color_future_dates="\033[0;30m" # Black
54 | color_weekends="\033[38;5;240m" # Gray
55 | color_current_month="\033[1;38;5;67m" # Bright Cyan
56 | color_line_highlight="\033[38;5;239m" # Dark Gray
57 | color_line="\033[0;30m" # Black
58 | color_resolved_cal="\033[38;5;246;48;5;236m" # Gray background with Light Gray text
59 | color_deadline_cal="\033[38;5;233;48;5;131m" # Dark Magenta background with Black text
60 | color_work_cal="\033[38;5;233;48;5;173m" # Orange background with Black text
61 | color_personal_cal="\033[38;5;233;48;5;101m" # Dark Red background with Black text
62 | color_birthday_cal="\033[38;5;233;48;5;66m" # Bright Blue background with Black text
63 | color_public_holiday_cal="\033[38;5;96m" # Dark Cyan
64 | color_school_holiday_cal="\033[38;5;139m" # Dark Magenta
65 | color_school_holiday_cal_parent="\033[38;5;102m" # Dark Gray
66 | color_vacation_cal="\033[38;5;139m" # Dark Magenta
67 | color_sick_leave_cal="\033[38;5;96m" # Dark Cyan
68 | color_resolved="\033[38;5;243m" # Dark Gray
69 | color_deadline="\033[38;5;167m" # Orange
70 | color_work="\033[38;5;173m" # Orange
71 | color_personal="\033[38;5;143m" # Dark Yellow
72 | color_birthday="\033[38;5;66m" # Bright Blue
73 | color_public_holiday="\033[38;5;96m" # Dark Cyan
74 | color_school_holiday="\033[38;5;139m" # Dark Magenta
75 | color_vacation="\033[38;5;139m" # Dark Magenta
76 | color_sick_leave="\033[38;5;96m" # Dark Cyan
77 | reset="\033[0m" # Reset color
78 | green="\033[0;32m" # Green
79 | yellow="\033[0;33m" # Yellow
80 |
81 | bullet_resolved="\xe2\x9c\x93"
82 | bullet_deadline="\xe2\x96\xa3"
83 | bullet_work="\xe2\x97\x8f"
84 | bullet_personal="\xe2\x97\x8f"
85 | bullet_birthday="\xe2\x97\x8f"
86 | bullet_public_holiday="\xe2\x98\x85"
87 | bullet_vacation="\xe2\x98\x85"
88 | bullet_sick_leave="\xe2\x96\xbd"
89 | bullet_school="\xe2\x97\x86"
90 |
91 | # Default time span for the next entry
92 | DEFAULT_DAYS_AHEAD=28
93 | # Default setting in months to determine when to trigger the next cleanup
94 | # Set to 0 for 'never perform automatic cleanup'
95 | DEFAULT_CLEANUP_FREQUENCY=6
96 | # Set a max. length that should be used for printing a calendar
97 | MAX_LINE_LENGTH=92
98 | # Hide past events in monthly details (Dynamic View)
99 | HIDE_PAST_EVENTS=0
100 | # Hide future events in monthly details (Dynamic View)
101 | HIDE_FUTURE_EVENTS=0
102 |
103 | # --- Don't modify anything below this line ---
104 |
105 | assign_globals() {
106 | last_overdue_date=${defaults["process_overdues"]}
107 | last_scheduled_date=${defaults["scheduled_cleanup"]}
108 | oha_last_imported=${defaults["oha_imported"]}
109 | oha_country_iso=${defaults["oha_country_iso"]}
110 | oha_language_iso=${defaults["oha_language_iso"]}
111 | oha_subdivision_iso=${defaults["oha_subdivision_iso"]}
112 | gca_skip=${defaults["gca_skip"]}
113 | verbose=${defaults["verbose"]}
114 | school=${defaults["school"]}
115 | legend=${defaults["legend"]}
116 | }
117 |
118 |
119 | SCRIPTPATH="$(
120 | cd -- "$(dirname "$0")" >/dev/null 2>&1
121 | pwd -P
122 | )"
123 |
124 | # Check if the file .dlinerc exists and source it if possible
125 | CONF="${SCRIPTPATH}/.dlinerc"
126 | if [ -f "$CONF" ]; then
127 | source ${CONF}
128 | fi
129 |
130 | UTILS="src/utils"
131 | DATA="src/data"
132 | API="src/api"
133 | default_filename="events_data.txt"
134 | default_log="settings.json"
135 | default_tsv="events_data.tsv"
136 |
137 | CONFIG_FILE=${SCRIPTPATH}/${DATA}/defaults.json
138 | ICON_FILE=${SCRIPTPATH}/${DATA}/dline_icon.png
139 | TSV_FILE=${SCRIPTPATH}/${DATA}/${default_tsv}
140 | DEFAULT_SETTINGS=${SCRIPTPATH}/${DATA}/${default_log}
141 | SETTINGS=${DEFAULT_SETTINGS}
142 |
143 | # Check if the DEFAULT_SETTINGS is empty then initialize it
144 | if [[ ! -s $DEFAULT_SETTINGS ]]; then
145 | cp ${CONFIG_FILE} ${DEFAULT_SETTINGS}
146 | fi
147 |
148 | LOCALE_FMT=$(locale -k LC_TIME | grep ^d_fmt | cut -d= -f2 | tr -d '"' | sed -e 's/y/Y/')
149 |
150 | current_date=$(date "+%Y/%m/%d %Y-%m-%d %H:%M")
151 | IFS=' ' read -r -a date_parts <<< "$current_date"
152 |
153 | TODAY=${date_parts[0]}
154 | current_date_dd=${date_parts[1]}
155 | CURRENT_TIME=${date_parts[2]}
156 | current_year=${TODAY:0:4}
157 | next_year=$((current_year + 1))
158 | next2_year=$((current_year + 2))
159 |
160 | REMINDERS_SET=0 # Initialize a flag
161 | REMINDER_DESC="" # Insert the bell icon into description
162 | num_gca=0 # Number of imported Google Calendars
163 | num_reminders=0 # Number of reminders
164 | num_categories=0 # Number of categories
165 | # Get current year and next year
166 |
167 | # Pass for the dcal function that combines several modes of operation
168 | ENFORCE="69kyI1l4FmC"
169 | CUSTOM_RANGE_KEY="u2XtbEVsfR"
170 | mode=""
171 |
172 | # Global variable to store all expired events
173 | lines=""
174 | # Regular expression for date validation (format: YYYY/MM/DD)
175 | date_regex="^[0-9]{4}/[0-9]{2}/[0-9]{2}$"
176 |
177 | source ${SCRIPTPATH}/${UTILS}/_model.sh
178 | source ${SCRIPTPATH}/${UTILS}/_controller.sh
179 | source ${SCRIPTPATH}/${UTILS}/_view.sh
180 |
181 | # Set the "active_file" from the default JSON file only
182 | json=$(jq -r '.' "${DEFAULT_SETTINGS}")
183 | defaults["active_file"]=$(echo "$json" | jq -r ".active_file")
184 |
185 | # Initialize the file for user's data
186 | INPUT_FILE=${SCRIPTPATH}/${DATA}/${default_filename}
187 | filename_from_json=${SCRIPTPATH}/${DATA}/${defaults["active_file"]}
188 | if [[ "${defaults["active_file"]}" != "" ]]; then
189 | INPUT_FILE="${filename_from_json}"
190 | else
191 | jq --arg file "${default_filename}" '.active_file = $file' ${DEFAULT_SETTINGS} > tmp.$$.json && mv tmp.$$.json ${DEFAULT_SETTINGS}
192 | fi
193 |
194 | if [[ ! -e ${INPUT_FILE} ]]; then
195 | touch ${INPUT_FILE}
196 | fi
197 |
198 | length=${#default_filename}
199 | if [[ "${default_filename}" != "${defaults["active_file"]}" ]]; then
200 | length=$((length+1)) # account for the "_" character
201 | fi
202 | prefix="${defaults["active_file"]:0:$((${#defaults["active_file"]}-length))}"
203 | if [[ "${prefix}" != "" ]]; then
204 | SETTINGS="${SCRIPTPATH}/${DATA}/${prefix}_${default_log}"
205 | TSV_FILE="${SCRIPTPATH}/${DATA}/${prefix}_${default_tsv}"
206 | fi
207 | # Check if the DEFAULT_SETTINGS is empty then initialize it
208 | if [[ ! -s $SETTINGS ]]; then
209 | cp ${CONFIG_FILE} ${SETTINGS}
210 | # Delete "active_file" from the non-default JSON files
211 | jq 'del(.active_file)' ${SETTINGS} > temp.json && mv temp.json ${SETTINGS}
212 | fi
213 |
214 | parse_json
215 | assign_globals
216 |
217 | # NOTE: This requires GNU getopt. On Mac OS X and FreeBSD, you have to install this
218 | # separately.
219 |
220 | # Option defaults
221 | OPT=""
222 |
223 | # Script version
224 | version="0.1.8-beta1"
225 |
226 | # getopts string
227 | # This string needs to be updated with the single character options (e.g. -f)
228 | opts="-o a:b:c:d:e:f:i:l:k:m:o:p:r:s:t:u:v:h:w:x -l add:,base,cleanup,delete:,export,filter:,import:,legend,kill,month:,open,print-details,resolve,school:,test:,update:,version,help,workdays:,xdg-open"
229 |
230 | # Gets the command name without path
231 | cmd() { echo $(basename $0); }
232 |
233 | # Prints an error message
234 | error() {
235 | echo "`cmd`: Extra arguments -- $*"
236 | echo "Try `cmd` -h' for more information."
237 | exit 1
238 | }
239 |
240 | # Help command output
241 | usage() {
242 | IFS="/"
243 | output1=$(date -d "+15 days" "+%Y/%m/%d")
244 | # Use the read command to split the output into separate variables
245 | read year month day <<< "$output1"
246 | unset IFS
247 | echo "\
248 | Usage:
249 | `cmd` -a; Add event (interactive mode)
250 | `cmd` -a ${year}/${month}/${day} 3 \"11:30 Lunch with Lucy\"; Add event directly
251 | `cmd`; Show current month calendar
252 | ;
253 | Options:
254 | -a, --add [yyyy/mm/dd] [x] [desc]; Add event. No args invokes interactive mode
255 | -b, --base; Manage your data, as snapshots of your changes
256 | ; (file management)
257 | -c, --clean; Remove old entries
258 | -d, --delete [GCA|OHA|pattern]; Delete imported calendars, or local matching entries.
259 | -e, --export; Export calendar to TSV format
260 | -f, --filter [x] [x] ...; Toggle visibility of one or more categories
261 | -h, --help; Show help
262 | -i, --import [TSV|GCA|OHA]; Import events from external sources
263 | -k, --kill; Terminate pending reminders
264 | -l, --legend; Toggle legend display
265 | -m, --month [yyyy/mm]; Show monthly calendar
266 | -o, --open; Open data file in terminal editor
267 | -p, --print-details; Toggle calendar details
268 | -r, --resolve; Interactive dialogue to resolve deadlines
269 | -s, --school [0|1]; Set school holidays as work days (0) or holidays (1)
270 | -t, --test [yyyy/mm/dd]; Set \"today\" for testing
271 | -u, --update [GCA|OHA] | [pattern] [yyyy/mm/dd] [x] [desc]; Update from APIs or local matching entries
272 | -v, --version; Show version
273 | -w, --workdays [start_date] [end_date]; Calculate workdays from optional start_date
274 | ; (default: today) to end_date
275 | -x, --xdg-open; Open data file in GUI editor
276 | " | column -t -s ";"
277 |
278 | echo
279 | echo "Event categories [x]:"
280 | view_categories | sed 's/^/ /'
281 | }
282 |
283 |
284 | # Error message
285 | error() {
286 | echo "`cmd`: invalid option -- '$1'"
287 | echo "Try '`cmd` -h' for more information."
288 | exit 1
289 | }
290 |
291 | # Sort the input file
292 | sort_input() {
293 | # Remove duplicate lines, empty lines and sort the file
294 | sort -u -o $INPUT_FILE $INPUT_FILE
295 | sed -i '/^$/d' $INPUT_FILE
296 | }
297 |
298 | # There's two passes here. The first pass handles the long options and
299 | # any short option that is already in canonical form. The second pass
300 | # uses `getopt` to canonicalize any remaining short options and handle
301 | # them
302 | for pass in 1 2; do
303 | while [ -n "$1" ]; do
304 | case $1 in
305 | --)
306 | shift
307 | break
308 | ;;
309 | -*) case $1 in
310 | -b | --clean) b="set" ;;
311 | -c | --clean) c="set" ;;
312 | -d | --delete)
313 | d="set"
314 | shift
315 | PATTERN="$1"
316 | case "${PATTERN^^}" in
317 | "GCA"|"OHA")
318 | if [ -n "$2" ]; then
319 | error "$@"
320 | fi
321 | ;;
322 | *)
323 | if [ -z "$PATTERN" ]; then
324 | error "$PATTERN"
325 | fi
326 | ;;
327 | esac
328 | ;;
329 | -e | --export) e="set" ;;
330 | -f | --filter)
331 | f="set"
332 | CODES=()
333 | shift
334 | # If no arguments provided after -f
335 | if [[ "$1" == -* || -z "$1" ]]; then
336 | toggle_show
337 | error "missing event category key"
338 | else
339 | while (( "$#" )); do
340 | CODE="$1"
341 | if [[ -n ${CODE} ]]; then
342 | if [[ -z ${defaults["categories[${CODE}][name]"]} ]]; then
343 | error "invalid category: ${CODE}"
344 | else
345 | # Store the valid categories in an array
346 | CODES+=("$CODE")
347 | fi
348 | fi
349 | shift
350 | done
351 | fi
352 | ;;
353 | -t | --test)
354 | t="set"
355 | shift
356 | DATE_PART=${1}
357 | shift
358 | TIME_PART=${2}
359 | if [[ ! ${DATE_PART} =~ ${date_regex} ]] || [[ -n $TIME_PART && ! $TIME_PART =~ ^[0-9]{2}:[0-9]{2}$ ]]; then
360 | # if [[ -n $TIME_PART && ! $TIME_PART =~ ^[0-9]{2}:[0-9]{2}$ ]]; then echo "TRUE"; else echo "FALSE"; fi
361 | error "${DATE_PART} ${TIME_PART}"
362 | fi
363 | ;;
364 | -a | --add)
365 | a="set"
366 | shift
367 | DLINE="$1"
368 | shift
369 | CODE="$1"
370 | shift
371 | NEW_LINE="$@"
372 | now=$(date -d "today 00:00:00" "+%s")
373 | if [[ -n "${DLINE}" ]] && [[ ! "${DLINE}" =~ ${date_regex} || $(date -d "${DLINE}" "+%s") -lt $now ]] || ! ( [[ -z "${DLINE}" && -z "${CODE}" && -z "${NEW_LINE}" ]] || [[ -n "${DLINE}" && -n "${CODE}" && -n "${NEW_LINE}" ]] ); then
374 | if [[ $(date -d "${DLINE}" "+%s") -lt $now ]]; then
375 | error "Adding events in the past?"
376 | elif [[ -n ${defaults["categories[$CODE][name]"]} ]]; then
377 | error "Invalid category: ${CODE}"
378 | fi
379 | error "${DLINE} ${CODE} ${NEW_LINE}"
380 | fi
381 | ;;
382 | -i | --import)
383 | i="set"
384 | shift
385 | TYPE="$1"
386 | case "${TYPE^^}" in
387 | "TSV"|"GCA"|"OHA")
388 | ;;
389 | *)
390 | error "$TYPE"
391 | ;;
392 | esac
393 | ;;
394 | -l | --legend) l="set" ;;
395 | -k | --kill) k="set" ;;
396 | -m | --month)
397 | m="set"
398 | shift
399 | MONTH="$1"
400 | if [[ ! ${MONTH} =~ ^[0-9]{4}\/[0-9]{2}$ ]]; then
401 | error "$MONTH"
402 | fi
403 | ;;
404 | -u | --update)
405 | u="set"
406 | shift
407 | PATTERN="$1"
408 | case "${PATTERN^^}" in
409 | "GCA"|"OHA")
410 | if [ -n "$2" ]; then
411 | error "$@"
412 | fi
413 | ;;
414 | *)
415 | shift
416 | NEW_LINE="$@"
417 | if [ -z "$PATTERN" ] || [ -z "$NEW_LINE" ]; then
418 | error "$PATTERN" "$NEW_LINE"
419 | fi
420 | ;;
421 | esac
422 | ;;
423 | -o | --open) o="set" ;;
424 | -p | --print-details) p="set" ;;
425 | -r | --resolve) r="set" ;;
426 | -s | --school)
427 | s="set"
428 | shift
429 | STUDENT_PARENT="$1"
430 | if [[ -n $STUDENT_PARENT ]]; then
431 | if [[ $STUDENT_PARENT -ne 0 && $STUDENT_PARENT -ne 1 ]]; then
432 | error "invalid argument: ${STUDENT_PARENT}, expected 0 or 1"
433 | fi
434 | else
435 | # When calling the function with no parameters,
436 | # it just displays the visibility of all categories
437 | toggle_school
438 | error "Do you take a break during School Holidays? Set 1 for yes, or 0 for no."
439 | fi
440 | ;;
441 | -w | --workdays)
442 | w="set"
443 | shift
444 | END_DATE="${1}"
445 | shift
446 | START_DATE="${1}"
447 | if [[ ! ${END_DATE} =~ ${date_regex} ]] || [[ -n $START_DATE && ! $START_DATE =~ ${date_regex} ]]; then
448 | error "${END_DATE} ${START_DATE}"
449 | elif [[ -n ${END_DATE} && -n ${START_DATE} && $START_DATE =~ ${date_regex} && $END_DATE =~ ${date_regex} ]]; then
450 | temp_date=${START_DATE}
451 | START_DATE=${END_DATE}
452 | END_DATE=${temp_date}
453 | fi
454 | ;;
455 | -v | --version) v="set" ;;
456 | -x | --xdg-open) x="set" ;;
457 | -h | --help) usage && exit 0 ;;
458 | --*) error $1 ;;
459 | -*) if [ $pass -eq 1 ]; then
460 | ARGS="$ARGS $1"
461 | else error $1; fi ;;
462 | esac ;;
463 | *) if [ $pass -eq 1 ]; then
464 | ARGS="$ARGS $1"
465 | else error $1; fi ;;
466 | esac
467 | shift
468 | done
469 | if [ $pass -eq 1 ]; then
470 | ARGS=$(getopt $opts $ARGS)
471 | if [ $? != 0 ]; then
472 | usage
473 | exit 2
474 | fi
475 | set -- $ARGS
476 | fi
477 | done
478 |
479 | # Handle positional arguments
480 | if [[ "$t" == "set" ]] && [[ $DATE_PART =~ ${date_regex} ]]; then
481 | if [[ -z $TIME_PART || $TIME_PART =~ ^[0-9]{2}:[0-9]{2}$ ]]; then
482 | dcal "$DATE_PART $TIME_PART"
483 | else
484 | dcal "$DATE_PART"
485 | fi
486 | unset t
487 | exit 0
488 | elif [[ "$a" == "set" ]]; then
489 | set_dcal "$DLINE" "$CODE" "$NEW_LINE"
490 | sort_input
491 | unset a
492 | exit 0
493 | elif [[ "$b" == "set" ]]; then
494 | base
495 | unset b
496 | exit 0
497 | elif [[ "$i" == "set" ]]; then
498 | case "${TYPE^^}" in
499 | "TSV")
500 | import_from_tsv
501 | ;;
502 | "GCA")
503 | [[ ${src_gca} -eq 0 ]] && source ${SCRIPTPATH}/${API}/gca.sh
504 | src_gca=1
505 | gca_init "IMPORT"
506 | ;;
507 | "OHA")
508 | [[ ${src_oha} -eq 0 ]] && source ${SCRIPTPATH}/${API}/oha.sh
509 | src_oha=1
510 | source ${SCRIPTPATH}/${API}/oha.sh
511 | oha "IMPORT"
512 | update_api_date_log
513 | ;;
514 | *)
515 | error "$TYPE"
516 | ;;
517 | esac
518 | sort_input
519 | unset i
520 | exit 0
521 | elif [[ "$l" == "set" ]]; then
522 | toggle_legend
523 | unset l
524 | exit 0
525 | elif [[ "$k" == "set" ]]; then
526 | kill_all_pids
527 | unset k
528 | exit 0
529 | elif [[ "$m" == "set" ]] && [[ ${MONTH} =~ ^[0-9]{4}\/[0-9]{2}$ ]]; then
530 | dcal "${MONTH}"
531 | unset m
532 | exit 0
533 | elif [[ "$c" == "set" ]]; then
534 | delete_line "${ENFORCE}"
535 | sort_input
536 | unset c
537 | exit 0
538 | elif [[ "$d" == "set" ]]; then
539 | case "${PATTERN^^}" in
540 | "GCA")
541 | [[ ${src_gca} -eq 0 ]] && source ${SCRIPTPATH}/${API}/gca.sh
542 | src_gca=1
543 | delete_gca_json
544 | ;;
545 | "OHA")
546 | [[ ${src_oha} -eq 0 ]] && source ${SCRIPTPATH}/${API}/oha.sh
547 | src_oha=1
548 | delete_oha
549 | echo
550 | ;;
551 | *)
552 | delete_line "${PATTERN}"
553 | ;;
554 | esac
555 | sort_input
556 | unset d
557 | exit 0
558 | elif [[ "$e" == "set" ]]; then
559 | export_to_tsv
560 | unset e
561 | exit 0
562 | elif [[ "$f" == "set" ]]; then
563 | toggle_show ${CODES[@]}
564 | unset f
565 | exit 0
566 | elif [[ "$u" == "set" ]]; then
567 | case "${PATTERN^^}" in
568 | "GCA")
569 | [[ ${src_gca} -eq 0 ]] && source ${SCRIPTPATH}/${API}/gca.sh
570 | src_gca=1
571 | gca_init "UPDATE"
572 | ;;
573 | "OHA")
574 | [[ ${src_oha} -eq 0 ]] && source ${SCRIPTPATH}/${API}/oha.sh
575 | src_oha=1
576 | oha "UPDATE"
577 | update_api_date_log
578 | ;;
579 | *)
580 | update_line "$PATTERN" "$NEW_LINE"
581 | ;;
582 | esac
583 | sort_input
584 | unset u
585 | exit 0
586 | elif [[ "$v" == "set" ]]; then
587 | echo "`cmd`: Version $version"
588 | unset v
589 | exit 0
590 | elif [[ "$w" == "set" ]]; then
591 | if [[ -z $START_DATE ]]; then
592 | START_DATE=$TODAY
593 | fi
594 | dcal "$START_DATE $END_DATE" "$CUSTOM_RANGE_KEY"
595 | unset w
596 | exit 0
597 | elif [[ "$o" == "set" ]]; then
598 | # Check if the EDITOR variable is set
599 | if [[ -z "$EDITOR" ]]; then
600 | echo "The EDITOR environment variable is not set. Please set it to your preferred text editor."
601 | echo
602 | exit 1
603 | fi
604 | # Open the file in the default editor
605 | $EDITOR ${INPUT_FILE}
606 | unset o
607 | exit 0
608 | elif [[ "$p" == "set" ]]; then
609 | toggle_print_details
610 | unset p
611 | exit 0
612 | elif [[ "$r" == "set" ]]; then
613 | dcal "$TODAY $CURRENT_TIME" "$ENFORCE"
614 | unset r
615 | exit 0
616 | elif [[ "$s" == "set" ]]; then
617 | toggle_school "$STUDENT_PARENT"
618 | unset s
619 | exit 0
620 | elif [[ "$x" == "set" ]]; then
621 | xdg-open ${INPUT_FILE}
622 | unset x
623 | exit 0
624 | elif [ -n "$*" ]; then
625 | error "$*"
626 | else
627 | # Run the main app when no arguments are passed
628 | dcal
629 | fi
630 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/src/utils/_model.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Add a new event
4 | # NOTE: The value is validated then stored in `./.deadline`
5 | set_dcal() {
6 | local selection
7 | current_date="${TODAY}"
8 | next_date=$(date -d "+1 day" "+%Y/%m/%d")
9 | current_datetime=$(date +%s)
10 |
11 | if [[ ! $deadline =~ ${date_regex} ]]; then
12 | deadline=$(date -d "+${DEFAULT_DAYS_AHEAD}days" +%Y/%m/%d 2>/dev/null)
13 | fi
14 |
15 | confirmed_date=${1}
16 | shift
17 | confirmed_code=${1}
18 | shift
19 | confirmed_desc=${@}
20 |
21 | if [[ -n "$confirmed_code" && ${#confirmed_code} == 1 ]]; then
22 | code=${confirmed_code}
23 | elif [[ -n "$confirmed_code" && ${#confirmed_code} > 1 ]]; then
24 | error "[yyyy/mm/dd] [x] [desc]"
25 | exit 1
26 | else
27 | # INPUT: category
28 | echo "Please select a category:"
29 | view_categories
30 | read -p "Enter a code of the category above [1]: " selection
31 | if [[ -z "$selection" ]]; then
32 | code="1"
33 | elif [[ $selection =~ ^[1-9a-z]$ ]]; then
34 | # Check if the entered code exists in the categories
35 | if [[ -n ${defaults["categories[$selection][name]"]} ]]; then
36 | code="$selection"
37 | else
38 | echo "Invalid selection: ${selection}"
39 | exit 1
40 | fi
41 | else
42 | echo "Invalid selection: ${selection}"
43 | exit 1
44 | fi
45 | fi
46 | read last_deadline <<< $(get_last_deadline)
47 | range=${defaults["categories[$code][range]"]}
48 |
49 | # INPUT: start_date, end_date
50 | if [ -n "$confirmed_date" ]; then
51 | start_date="${confirmed_date}"
52 | end_date="${confirmed_date}"
53 | desc=$confirmed_desc
54 | force="$ENFORCE"
55 | else
56 | if (( range == 1 )); then
57 | if [ -n "$BASH_VERSION" ]; then
58 | echo -ne "${MSG['start_date']}"
59 | read -r -ei "$deadline" -p " [$(echo -e "${yellow}${MSG['date_format']}${reset}")]: " start_date
60 | echo -ne "${MSG['end_date']}"
61 | read -r -ei "$start_date" -p " [$(echo -e "${yellow}${MSG['date_format']}${reset}")]: " end_date
62 | else
63 | vared -ep "${MSG['start_date_zsh']}" deadline
64 | start_date=${(q)deadline}
65 | end_date=${(q)start_date}
66 | vared -ep "${MSG['end_date_zsh']}" end_date
67 | fi
68 | start_date=${start_date:-"$deadline"}
69 | end_date=${end_date:-"$deadline"}
70 | else
71 | if [ -n "$BASH_VERSION" ]; then
72 | echo -ne "${MSG['new_date']}"
73 | read -r -ei "$deadline" -p " [$(echo -e "${yellow}${MSG['date_format']}${reset}")]: " start_date
74 | else
75 | vared -ep "${MSG['new_date_zsh']}" deadline
76 | start_date=${(q)deadline}
77 | fi
78 | start_date=${start_date:-"$deadline"}
79 | end_date=$start_date
80 | fi
81 | fi
82 |
83 | if [[ $start_date =~ ${date_regex} && $end_date =~ ${date_regex} ]]; then
84 | # Use the date command once to get the date in seconds and in the locale format
85 | date_output=$(date -d "$start_date" "+%s ${LOCALE_FMT}" 2>/dev/null)
86 |
87 | # Use parameter expansion to extract the date in seconds and in the locale format
88 | start_date_sec=${date_output%% *}
89 | DEADLINE_FMT=${date_output#* }
90 | if [[ -z "$start_date_sec" ]]; then
91 | echo -ne "Invalid date format for start date: ${start_date}\n"
92 | exit 1
93 | fi
94 |
95 | end_date_sec=$(date -d "$end_date" +%s 2>/dev/null)
96 | if [[ -z "$end_date_sec" ]]; then
97 | echo -ne "Invalid date format for end date: ${end_date}\n"
98 | exit 1
99 | fi
100 |
101 | if [[ $start_date_sec -gt $end_date_sec ]]; then
102 | echo "Error: invalid date range."
103 | exit 1
104 | fi
105 | else
106 | echo -ne "Invalid date format. Please ensure both dates are in the format: yyyy/mm/dd\n"
107 | exit 1
108 | fi
109 |
110 | if [[ $force == "$ENFORCE" ]]; then
111 | DESC=${DESC:-"$desc"}
112 | else
113 | if [[ -z $desc ]]; then
114 | if [ -n "$BASH_VERSION" ]; then
115 | echo -ne "${MSG['new_desc']}"
116 | last_deadline=${last_deadline:-"${MSG['default_desc']}"}
117 | read -r -ei "${desc}" -p " [$(echo -e "${yellow}${last_deadline}${reset}")]: " DESC
118 | else
119 | vared -ep "${MSG['new_desc_zsh']}" desc
120 | DESC="${(q)desc}"
121 | fi
122 | fi
123 | DESC=${DESC:-"${last_deadline}"}
124 | fi
125 |
126 | if [[ -z ${DESC} ]]; then
127 | echo "Error: Description is missing"
128 | exit 1
129 | fi
130 |
131 | # Store events in a temporary array
132 | temp_events=()
133 |
134 | for ((date_sec=$start_date_sec; date_sec<=$end_date_sec; date_sec+=86400)); do
135 | date=$(date -d "@$date_sec" +%Y/%m/%d)
136 | # Check if event exists in the input file
137 | while grep -q "$date $code ${DESC}" "$INPUT_FILE" || grep -q "$date . ${DESC}" "$INPUT_FILE"; do
138 | if grep -q "$date $code ${DESC}" "$INPUT_FILE"; then
139 | category_name=${defaults["categories[$code][name]"]}
140 | echo
141 | echo -e "$category_name: [${yellow}$date${reset}] ${yellow}${DESC}${reset}"
142 | echo
143 | echo -en "This event already exists.\nWould you like to enter a different description? [Y/n] "
144 | read input_yn
145 | case $input_yn in
146 | [yY][eE][sS]|[yY]|"")
147 | if [ -n "$BASH_VERSION" ]; then
148 | echo -ne "${MSG['new_desc']}"
149 | last_deadline=${last_deadline:-"${MSG['default_desc']}"}
150 | read -r -ei "$desc" -p " [$(echo -e "${yellow}${last_deadline}${reset}")]: " DESC
151 | else
152 | vared -ep "${MSG['new_desc_zsh']}" desc
153 | DESC=${(q)desc}
154 | fi
155 | if [[ force == "$ENFORCE" ]]; then
156 | DESC=${DESC:-"$desc"}
157 | else
158 | DESC=${DESC:-"$last_deadline"}
159 | fi
160 | ;;
161 | *)
162 | # interrupt the loop and cancel the operation of insertion
163 | echo "Operation cancelled"
164 | exit 1
165 | ;;
166 | esac
167 | else
168 | echo -en "The same event under a different category already exists.\nWould you like to update its category instead? [Y/n] "
169 | read input_yn
170 | case $input_yn in
171 | [yY][eE][sS]|[yY]|"")
172 | # update the status of the event from resolved to pending
173 | # start_date_sec=$(date -d "$start_date" +%s)
174 | # end_date_sec=$(date -d "$end_date" +%s)
175 | # Create an associative array to store the dates in the new range
176 | declare -A new_dates
177 | for ((date_sec=$start_date_sec; date_sec<=$end_date_sec; date_sec+=86400)); do
178 | new_date=$(date -d "@$date_sec" +%Y/%m/%d)
179 | new_dates["$new_date"]=1
180 | done
181 |
182 | # Read the file line by line
183 | while IFS= read -r line; do
184 | read -r -a array <<< "$line"
185 | old_date="${array[0]}"
186 | old_description="${array[2]}"
187 |
188 | # Convert old_date to seconds for comparison
189 | IFS="/" read -r -a date_parts <<< "$old_date"
190 | old_date_sec=$(( (date_parts[0] - 1970) * 31536000 + (date_parts[1] - 1) * 2592000 + (date_parts[2] - 1) * 86400 ))
191 |
192 | # If a line's date is within the new date range and its description matches $DESC
193 | if (( old_date_sec >= start_date_sec && old_date_sec <= end_date_sec )) && [[ "$old_description" == "${DESC}" ]]; then
194 | # Change the category code to $code and unset the date in new_dates
195 | echo "$old_date $code ${DESC}"
196 | unset new_dates["$old_date"]
197 | else
198 | echo "$line"
199 | fi
200 | done < "$INPUT_FILE" >| tempfile
201 |
202 | # Add the remaining dates in new_dates to the file
203 | for new_date in "${!new_dates[@]}"; do
204 | echo "$new_date $code ${DESC}" >> tempfile
205 | done
206 |
207 | mv tempfile "$INPUT_FILE"
208 | echo "Event category updated."
209 | return
210 | ;;
211 | *)
212 | # cancel the operation
213 | echo "Operation cancelled"
214 | return
215 | ;;
216 | esac
217 | fi
218 | done
219 | validate_reminder "$date" "$code" "${DESC}"
220 | if [[ -n $REMINDER_DESC ]]; then
221 | temp_events+=("$date $code ${REMINDER_DESC}")
222 | unset $REMINDER_DESC
223 | else
224 | temp_events+=("$date $code ${DESC}")
225 | fi
226 | done
227 | # Write all new events to the file
228 | cleanup_inactive_pids
229 | printf "%s\n" "${temp_events[@]}" >> "$INPUT_FILE"
230 | echo $(expr '(' $start_date_sec - $(date +%s) + 86399 ')' / 86400) " days until deadline ($DEADLINE_FMT)"
231 | }
232 |
233 |
234 | # Sort the INPUT file by dates
235 | # use the grep command to output all deadline dates with corresponding descriptions for the given month
236 | # NOTE: argument 1 format: YYYY/MM
237 | events_in_month() {
238 | # Output all deadline dates with corresponding descriptions for the given month
239 | if [[ ${HIDE_PAST_EVENTS} -ne 0 && ${HIDE_FUTURE_EVENTS} -eq 0 && $display_month -ne 1 ]]; then
240 | # Hide all past events
241 | awk -v year="$year" -v month="$month_zero" -v today="$day_zero" '
242 | BEGIN {
243 | FS="/"
244 | }
245 | {
246 | # Extract the day part from the $3
247 | day=substr($3, 1, 2)
248 | if ($1 == year && $2 == month && day >= today) {
249 | print
250 | } else if ($1 > year || ($1 == year && $2 > month)) {
251 | exit
252 | }
253 | }
254 | ' <<< "${sorted_lines}"
255 | elif [[ ${HIDE_PAST_EVENTS} -ne 0 && ${HIDE_FUTURE_EVENTS} -ne 0 && $display_month -ne 1 ]]; then
256 | # Show only today's agenda
257 | awk -v year="$year" -v month="$month_zero" -v today="$day_zero" '
258 | BEGIN {
259 | FS="/"
260 | }
261 | {
262 | # Extract the day part from the $3
263 | day=substr($3, 1, 2)
264 | if ($1 == year && $2 == month && day == today) {
265 | print
266 | } else if (($1 == year && $2 == month && day > today) || ($1 == year && $2 > month) || $1 > year) {
267 | exit
268 | }
269 | }
270 | ' <<< "${sorted_lines}"
271 | elif [[ ${HIDE_PAST_EVENTS} -eq 0 && ${HIDE_FUTURE_EVENTS} -ne 0 && $display_month -ne 1 ]]; then
272 | # Hide all upcoming events
273 | awk -v year="$year" -v month="$month_zero" -v today="$day_zero" '
274 | BEGIN {
275 | FS="/"
276 | }
277 | {
278 | # Extract the day part from the $3
279 | day=substr($3, 1, 2)
280 | if ($1 == year && $2 == month && day <= today) {
281 | print
282 | } else if (($1 == year && $2 == month && day > today) || ($1 == year && $2 > month) || $1 > year) {
283 | exit
284 | }
285 | }
286 | ' <<< "${sorted_lines}"
287 | else
288 | # Don't hide past events
289 | grep "^$year/$month_zero" <<<${sorted_lines}
290 | fi
291 | }
292 |
293 |
294 | update_line() {
295 | # Check if the correct number of arguments is provided
296 | if [ $# -ne 2 ]; then
297 | echo "Usage: `cmd` "
298 | exit 1
299 | fi
300 |
301 | # Assign the arguments to variables
302 | if [[ "$1" == *[\^\$]* ]]; then
303 | pattern="$1"
304 | else
305 | pattern="^$1.*$"
306 | fi
307 | new_line=$2
308 |
309 | # Find the line matching the pattern
310 | line=$(grep -v -e '^$' "$INPUT_FILE" | grep "$pattern")
311 |
312 | # Check if more than one line is found
313 | if [[ ! -z "$line" && $(echo "$line" | wc -l) -gt 1 ]]; then
314 | echo "Warning: More than one line matches the pattern ${pattern}"
315 | echo "$line"
316 | exit 1
317 | elif [[ -z "$line" ]]; then
318 | echo "Warning: No line matches the pattern ${pattern}"
319 | exit 1
320 | fi
321 |
322 | # Split the new line into three parts
323 | date_part=$(echo "$new_line" | cut -d " " -f 1)
324 | code_part=$(echo "$new_line" | cut -d " " -f 2)
325 | description_part=$(echo "$new_line" | cut -d " " -f 3-)
326 |
327 | # Check if the date is in the correct format
328 | # if ! [[ $date_part =~ ${date_regex} ]]; then
329 | if ! new_date=$(date -d "$date_part" +%Y/%m/%d 2>/dev/null); then
330 | echo "Error: The date is not in the correct format"
331 | exit 1
332 | fi
333 |
334 | # Check if the code is a single-digit number
335 | if (( code_part > 9 )); then
336 | echo "Error: The code is not a single-digit number"
337 | exit 1
338 | fi
339 |
340 | # Check if the description is not empty
341 | if [ -z "$description_part" ]; then
342 | echo "Error: The description is empty"
343 | exit 1
344 | fi
345 |
346 | # Replace the line with the new line
347 | # sed -i "s#$pattern#$new_date $code_part $description_part#" ${INPUT_FILE} && sort -k1.1,1.10 ${INPUT_FILE} -o ${INPUT_FILE}
348 | set +o noclobber
349 | awk -v pattern="$pattern" -v new="$new_date $code_part $description_part" 'BEGIN{FS=OFS=" "} $0 ~ pattern {$0=new} 1' ${INPUT_FILE} >| tmpfile
350 | if [[ -s tmpfile ]]; then
351 | mv tmpfile ${INPUT_FILE}
352 | else
353 | echo "No lines matching the pattern found."
354 | fi
355 | set -o noclobber
356 |
357 | echo "$new_date $code_part $description_part"
358 | echo "Line updated successfully"
359 | }
360 |
361 |
362 | # Get all entries prior to start_timestamp - seconds_in_months
363 | expired_lines() {
364 | # Calculate the cutoff date
365 | cutoff_date=$(date -d"@$((start_timestamp - seconds_in_months))" +'%Y/%m/%d')
366 | lines=""
367 |
368 | while IFS= read -r line; do
369 | # Extract the date from the line
370 | line_date=${line:0:10}
371 |
372 | # If the line date is earlier than the cutoff date, add the line to lines
373 | if [[ "$line_date" < "$cutoff_date" ]]; then
374 | lines+=$'\n'$line
375 | fi
376 | done < ${INPUT_FILE}
377 |
378 | # Remove leading newlines
379 | lines="${lines#"${lines%%[!$'\n']*}"}"
380 | # Remove trailing newlines
381 | lines="${lines%"${lines##*[!$'\n']}"}"
382 | }
383 |
384 |
385 | delete_line() {
386 | # Check if the correct number of arguments is provided
387 | if [ $# -ne 1 ]; then
388 | echo "Usage: `cmd` "
389 | exit 1
390 | fi
391 |
392 | # Assign the argument to a variable
393 | pattern=$1
394 |
395 | # Find the lines matching the pattern
396 | if [[ $pattern == "$ENFORCE" ]]; then
397 | expired_lines
398 | else
399 | lines=$(grep -ve '^[[:space:]]*$' "${INPUT_FILE}" | grep "$pattern")
400 | # lines=$(grep "$pattern" ${INPUT_FILE})
401 | fi
402 |
403 | # Check if no lines are found
404 | if [ -z "$lines" ]; then
405 | echo "No lines found for deletion"
406 | exit 1
407 | fi
408 |
409 | # Print the lines matching the pattern
410 | echo "$lines"
411 | echo
412 |
413 | local lines_to_delete=$(echo "$lines" | wc -l)
414 | # Check if more than one line is found
415 | if [[ $lines_to_delete -gt 1 ]]; then
416 | echo -e "There are ${alert}$lines_to_delete${reset} entries found for deletion."
417 | fi
418 |
419 | # Ask the user if they want to delete the lines
420 | read -p "Are you sure you want to delete the above line(s)? (y/n) " answer
421 |
422 | # Delete the lines if the user answers yes
423 | if [ "$answer" = "y" ]; then
424 | set +o noclobber
425 | if [[ $pattern == "$ENFORCE" ]]; then
426 | # Create a temporary file
427 | tmpfile=$(mktemp)
428 | # Iterate over each line in the input file
429 | while IFS= read -r line; do
430 | # If the line is not in the lines to be deleted, write it to the temporary file
431 | if ! echo "$lines" | grep -Fxq "$line"; then
432 | echo "$line" >> "$tmpfile"
433 | fi
434 | done < ${INPUT_FILE}
435 | # Replace the input file with the temporary file
436 | mv "$tmpfile" ${INPUT_FILE}
437 | else
438 | # Delete the line(s) that match a given pattern
439 | awk -v pattern="$pattern" 'BEGIN{FS=OFS=" "} $0 !~ pattern' ${INPUT_FILE} >| tmpfile
440 | if [[ -s tmpfile ]]; then
441 | mv tmpfile ${INPUT_FILE}
442 | else
443 | echo "All lines match the pattern."
444 | if [[ -e tmpfile ]]; then
445 | rm tmpfile
446 | fi
447 | fi
448 | fi
449 | set -o noclobber
450 | echo "Line(s) deleted successfully"
451 | return 0
452 | else
453 | echo "Operation cancelled"
454 | return 1
455 | fi
456 | }
457 |
458 |
459 | scheduled_cleanup() {
460 | # Update the last execution date for this use case
461 | jq --argjson date "$start_timestamp" '.scheduled_cleanup = $date' $SETTINGS > tmp.$$.json && mv tmp.$$.json $SETTINGS
462 |
463 | while true; do
464 | echo
465 | echo -e "${alert}This will delete all events that are older than ${DEFAULT_CLEANUP_FREQUENCY} months.${reset}"
466 | echo -en "Would you like to perform automatic cleanup? [Y/n] "
467 | read input_yn
468 | case $input_yn in
469 | [yY][eE][sS]|[yY]|"")
470 | # Call your function
471 | echo
472 | delete_line "$ENFORCE"
473 | break
474 | ;;
475 | *)
476 | echo "Ok, you could always clean it manually."
477 | break
478 | ;;
479 | esac
480 | done
481 | }
482 |
483 |
484 | export_to_tsv() {
485 | # Check if the required input files exist
486 | if [[ ! -f $INPUT_FILE ]] || [[ ! -f $SETTINGS ]]; then
487 | echo "Error: Missing input file(s)."
488 | echo
489 | return 1
490 | fi
491 |
492 | # Process the input file line by line
493 | while IFS=' ' read -r date key desc; do
494 | # Add the category name as the fourth column
495 | echo -e "$date\t$key\t$desc\t"${defaults["categories[$key][name]"]}
496 | done < $INPUT_FILE >| $TSV_FILE
497 |
498 | # Get the current date
499 | todays_date=$(date +"%Y/%m/%d")
500 |
501 | # Add the export date as an extended attribute to the TSV file
502 | setfattr -n user.export_date -v "Export date: $todays_date" ${TSV_FILE}
503 |
504 | # Open the TSV file
505 | xdg-open ${TSV_FILE} > /dev/null 2>&1
506 | }
507 |
508 |
509 | import_from_tsv() {
510 | # Check if the required input files exist
511 | if [[ ! -f $TSV_FILE ]]; then
512 | echo "Error: The TSV file does not exist. Proceeding with export as a required step prior to this action..."
513 | echo
514 | export_to_tsv
515 | return 1
516 | fi
517 |
518 | # Print the last export data on screen
519 | getfattr -n user.export_date ${TSV_FILE} 2>/dev/null | cut -d '"' -f 2
520 |
521 | echo "Select an option:"
522 | echo -e " [${yellow}1${reset}] Overwrite"
523 | echo -e " [${yellow}2${reset}] Append new values"
524 | echo -e " [${yellow}3${reset}] Cancel"
525 | echo
526 | read -p "Enter your choice [1]: " choice
527 |
528 | # Validate the data in the TSV file
529 | while IFS=$'\t' read -r date key desc category_name; do
530 | if [[ ! $date =~ ${date_regex} ]] || [[ ${#key} -ne 1 ]] || [[ -z $desc ]]; then
531 | echo "Error: Invalid data in the TSV file:"
532 | echo -e "${date}\t${key}\t${desc}"
533 | return 1
534 | fi
535 | done < $TSV_FILE
536 |
537 | case ${choice:-1} in
538 | 1)
539 | # Ask the user if they want to overwrite the existing content
540 | read -p "Are you sure you want to overwrite your existing events? (Y/n): " answer
541 | case ${answer:-y} in
542 | [yY][eE][sS]|[yY]|"")
543 | # Overwrite the existing content
544 | while IFS=$'\t' read -r date key desc category_name; do
545 | # Trim leading and trailing spaces in the description
546 | desc=$(echo "$desc" | sed 's/^ *//;s/ *$//')
547 | echo -e "${date} ${key} ${desc}"
548 | done < ${TSV_FILE} >| ${INPUT_FILE}
549 | ;;
550 | *)
551 | echo "Ok, no worries."
552 | return 0
553 | ;;
554 | esac
555 | ;;
556 | 2)
557 | # Append values to the end of the input file
558 | while IFS=$'\t' read -r date key desc category_name; do
559 | # Trim leading and trailing spaces in the description
560 | desc=$(echo "$desc" | sed 's/^ *//;s/ *$//')
561 | echo -e "${date} ${key} ${desc}"
562 | done < ${TSV_FILE} >> ${INPUT_FILE}
563 | ;;
564 | *)
565 | echo "Operation cancelled"
566 | return 0
567 | ;;
568 | esac
569 |
570 | echo "The process has been completed. The '${INPUT_FILE}' has been updated."
571 | }
572 |
573 |
574 | sanitize() {
575 | # Replace spaces with underscores
576 | local CLEAN=${1// /_}
577 | # Clean out anything that's not alphanumeric or an underscore
578 | CLEAN=${CLEAN//[^a-zA-Z0-9_]/}
579 | # Remove trailing underscores
580 | CLEAN=$(echo "$CLEAN" | sed 's/_*$//')
581 | # Lowercase with TR
582 | echo -n $CLEAN | tr A-Z a-z
583 | }
584 |
585 |
586 | # Print available files
587 | file_options() {
588 | maxsize=1
589 | i=1
590 | get_files
591 |
592 | while read -r line; do
593 | size=$(echo ${line} | awk '{print $1}')
594 | [[ ${maxsize} -lt ${#size} ]] && maxsize=${#size}
595 | done< <(echo "${data}" | awk '{printf "%s\n", $6}')
596 |
597 | while read -r line; do
598 | size=$(echo ${line} | awk '{print $1}')
599 | date=$(echo ${line} | awk '{print $2}')
600 | time=$(echo ${line} | awk '{print $3}')
601 | prefix=$(echo ${line} | awk '{print $4}')
602 |
603 | printf -v size "%*s" $maxsize "$size"
604 | if [[ -f "${SCRIPTPATH}/${DATA}/${default_filename}" && -w "${SCRIPTPATH}/${DATA}/${default_filename}" && ${prefix^^} == "DEFAULT" ]]; then
605 | echo -e " [${green}${i}${reset}] ${size} ${date} ${time} ${green}${prefix}${reset}"
606 | tags+=("${prefix}")
607 | elif [[ -f "${SCRIPTPATH}/${DATA}/${prefix}_${default_filename}" && -w "${SCRIPTPATH}/${DATA}/${prefix}_${default_filename}" ]]; then
608 | echo -e " [${green}${i}${reset}] ${size} ${date} ${time} ${green}${prefix}${reset}"
609 | tags+=("${prefix}")
610 | fi
611 | (( i++ ))
612 | done< <(echo "${data}" | awk '{printf "%s %s %s %s\n", $1, $2, $3, $4}')
613 | echo
614 | }
615 |
616 |
617 | new_file() {
618 | # Delete a file
619 | sanitized=""
620 | if [[ ${new} -ne 1 ]]; then
621 | echo "Available files:"
622 | file_options
623 | if [[ ${#tags[@]} -eq 0 ]]; then
624 | echo "No files."
625 | echo
626 | fi
627 | fi
628 | prefix=""
629 | echo -e " Sample filename: ${yellow}prefix${reset}_${default_filename}"
630 | echo
631 | while [[ ! $FILE =~ ^[A-Za-z0-9_]+$ ]] || [[ " ${tags[@]} " =~ " ${sanitized} " ]]; do
632 | read -p "Enter a prefix for the new file [a-z0-9_]: " FILE
633 | sanitized="$(sanitize "${FILE}")"
634 | done
635 | sanitized+="_"
636 | if [[ "${prefix}" != "${sanitized}" ]]; then
637 | touch "${SCRIPTPATH}/${DATA}/${sanitized}${default_filename}"
638 | touch "${SCRIPTPATH}/${DATA}/${sanitized}${default_log}"
639 | echo "New file created: '${sanitized}${default_filename}'."
640 | fi
641 | }
642 |
643 |
644 | view_file() {
645 | # Delete a file
646 | echo "Available files:"
647 | file_options
648 | prefix=""
649 | if [[ ${#tags[@]} -eq 0 ]]; then
650 | new=1
651 | echo "Nothing to view, create a new file instead."
652 | echo
653 | new_file
654 | return
655 | fi
656 | opt=$(( ${#tags[@]} ))
657 | while [[ ! $FILE =~ ^[1-${opt}]$ ]]; do
658 | read -p "Choose a file to view [1-${opt}]: " FILE
659 | done
660 | (( FILE-- ))
661 | if [[ "${tags[$FILE]^^}" != "DEFAULT" ]]; then
662 | prefix="${tags[$FILE]}_"
663 | fi
664 |
665 | # Define options
666 | options=("View with bat/cat" "View with fzf" "View with less/more" "Copy path to clipboard" "Back")
667 |
668 | custom_select
669 |
670 | # Process user's choice
671 | case $REPLY in
672 | 1)
673 | # Check if bat is installed
674 | if command -v bat >/dev/null 2>&1; then
675 | echo "Opening file '${prefix}${default_filename}' with bat..."
676 | bat "${SCRIPTPATH}/${DATA}/${prefix}${default_filename}"
677 | else
678 | echo "Opening file '${prefix}${default_filename}' with cat..."
679 | cat "${SCRIPTPATH}/${DATA}/${prefix}${default_filename}"
680 | fi
681 | ;;
682 | 2)
683 | # Check if fzf is installed
684 | if command -v fzf >/dev/null 2>&1; then
685 | echo "Opening file '${prefix}${default_filename}' with fzf..."
686 | cat "${SCRIPTPATH}/${DATA}/${prefix}${default_filename}" | fzf
687 | else
688 | echo "Error: 'fzf' is not installed"
689 | fi
690 | ;;
691 | 3)
692 | # Check if less is installed
693 | if command -v less >/dev/null 2>&1; then
694 | echo "Opening file '${prefix}${default_filename}' with less..."
695 | less "${SCRIPTPATH}/${DATA}/${prefix}${default_filename}"
696 | else
697 | echo "Opening file '${prefix}${default_filename}' with more..."
698 | more "${SCRIPTPATH}/${DATA}/${prefix}${default_filename}"
699 | fi
700 | ;;
701 | 4)
702 | echo -n "${SCRIPTPATH}/${DATA}/${prefix}${default_filename}" | xclip -selection clipboard
703 | echo "Full file path copied to clipboard."
704 | echo
705 | return
706 | ;;
707 | 5)
708 | return
709 | ;;
710 | esac
711 | echo "File closed."
712 | }
713 |
714 |
715 | select_file() {
716 | # Select a file
717 | unset REPLY
718 | echo "Available files:"
719 | file_options
720 | prefix=""
721 | if [[ ${#tags[@]} -eq 0 ]]; then
722 | new=1
723 | echo "Nothing to select, let's create a new file instead."
724 | echo
725 | new_file
726 | echo
727 | echo "Available files:"
728 | file_options
729 | fi
730 | opt=$(( ${#tags[@]} ))
731 | if [[ ${opt} -gt 1 ]]; then
732 | while [[ ! $REPLY =~ ^[1-${opt}]$ ]]; do
733 | read -p "Choose a file to be selected [1-${opt}]: " REPLY
734 | done
735 | (( REPLY-- ))
736 | if [[ "${tags[$REPLY]^^}" != "DEFAULT" ]]; then
737 | prefix="${tags[$REPLY]}_"
738 | fi
739 | if [[ -n $REPLY ]]; then
740 | yes_no "Select the file '${prefix}${default_filename}'?"
741 | fi
742 | else
743 | [[ -n "${tags[0]}" && "${tags[0]}" != "DEFAULT" ]] && prefix="${tags[0]}_" || prefix=""
744 | user_input="yes"
745 | fi
746 | if [[ $user_input == "yes" ]]; then
747 | jq --arg file "${prefix}${default_filename}" '.active_file = $file' ${DEFAULT_SETTINGS} > tmp.$$.json && mv tmp.$$.json ${DEFAULT_SETTINGS}
748 | defaults["active_file"]="${prefix}${default_filename}"
749 | INPUT_FILE="${SCRIPTPATH}/${DATA}/${prefix}${default_filename}"
750 | SETTINGS="${SCRIPTPATH}/${DATA}/${prefix}${default_log}"
751 | TSV_FILE="${SCRIPTPATH}/${DATA}/${prefix}${default_tsv}"
752 | touch ${SETTINGS}
753 | echo "New file selected."
754 | else
755 | echo "No action taken, the previous selection remains intact."
756 | fi
757 | }
758 |
759 |
760 | edit_file() {
761 | # Delete a file
762 | echo "Available files:"
763 | file_options
764 | prefix=""
765 | if [[ ${#tags[@]} -eq 0 ]]; then
766 | new=1
767 | echo "Nothing to edit, create a new file instead."
768 | echo
769 | new_file
770 | echo
771 | echo "Available files:"
772 | file_options
773 | fi
774 | opt=$(( ${#tags[@]} ))
775 | while [[ ! $FILE =~ ^[1-${opt}]$ ]]; do
776 | read -p "Choose a file to be edited [1-${opt}]: " FILE
777 | done
778 | (( FILE-- ))
779 | if [[ "${tags[$FILE]^^}" != "DEFAULT" ]]; then
780 | prefix="${tags[$FILE]}_"
781 | fi
782 |
783 | # Define options
784 | options=("Open in terminal" "Open in GUI" "Back")
785 |
786 | custom_select
787 |
788 | echo "Opening file '${prefix}${default_filename}'..."
789 | # Process user's choice
790 | case $REPLY in
791 | 1)
792 | # Check if the EDITOR variable is set
793 | if [[ -z "$EDITOR" ]]; then
794 | echo "The EDITOR environment variable is not set. Please set it to your preferred text editor."
795 | echo
796 | return
797 | fi
798 | $EDITOR "${SCRIPTPATH}/${DATA}/${prefix}${default_filename}"
799 | ;;
800 | 2)
801 | xdg-open "${SCRIPTPATH}/${DATA}/${prefix}${default_filename}"
802 | ;;
803 | 3)
804 | return
805 | ;;
806 | esac
807 | }
808 |
809 |
810 | rename_file() {
811 | # Delete a file
812 | sanitized=""
813 | echo "Available files:"
814 | file_options
815 | prefix=""
816 | if [[ ${#tags[@]} -eq 0 ]] || [[ ${#tags[@]} -eq 1 && " ${tags[@]} " =~ " DEFAULT " ]]; then
817 | new=1
818 | echo "Nothing to rename, create a new file instead."
819 | echo
820 | new_file
821 | return
822 | fi
823 | opt=$(( ${#tags[@]} ))
824 | while [[ ! $REPLY =~ ^[1-${opt}]$ ]]; do
825 | read -p "Choose a file to be renamed [1-${opt}]: " REPLY
826 | done
827 | (( REPLY-- ))
828 | if [[ "${tags[$REPLY]^^}" != "DEFAULT" ]]; then
829 | prefix="${tags[$REPLY]}_"
830 | fi
831 | if [[ -n $REPLY ]]; then
832 | yes_no "Are you sure to rename the file '${prefix}${default_filename}'?"
833 | fi
834 | if [[ $user_input == "yes" ]]; then
835 | echo
836 | if [[ "${prefix}" != "" ]]; then
837 | prefix_nd="${prefix:0:-1}"
838 | echo -e " Current filename: ${yellow}${prefix_nd}${reset}_${default_filename}"
839 | else
840 | echo -e " Old filename: ${default_filename}"
841 | echo -e " New filename: ${yellow}prefix${reset}_${default_filename}"
842 | fi
843 | echo
844 | while [[ ! $FILE =~ ^[A-Za-z0-9_]+$ ]] || [[ " ${tags[@]} " =~ " ${sanitized} " ]]; do
845 | read -p "Enter a new prefix to the old file name [a-z0-9_]: " FILE
846 | sanitized="$(sanitize "${FILE}")"
847 | done
848 | sanitized+="_"
849 | if [[ "${prefix}" != "${sanitized}" ]]; then
850 | mv "${SCRIPTPATH}/${DATA}/${prefix}${default_filename}" "${SCRIPTPATH}/${DATA}/${sanitized}${default_filename}"
851 | NEW_SETTINGS="${SCRIPTPATH}/${DATA}/${sanitized}${default_log}"
852 | NEW_TSV_FILE="${SCRIPTPATH}/${DATA}/${sanitized}${default_tsv}"
853 | # Check if the SETTINGS is empty then initialize it
854 | if [[ -e "${SCRIPTPATH}/${DATA}/${prefix}${default_log}" ]]; then
855 | mv "${SCRIPTPATH}/${DATA}/${prefix}${default_log}" "${NEW_SETTINGS}"
856 | else
857 | touch ${NEW_SETTINGS}
858 | fi
859 | SETTINGS="${NEW_SETTINGS}"
860 | # Check if the TSV_FILE is empty then initialize it
861 | if [[ -e "${SCRIPTPATH}/${DATA}/${prefix}${default_tsv}" ]]; then
862 | mv "${SCRIPTPATH}/${DATA}/${prefix}${default_tsv}" "${NEW_TSV_FILE}"
863 | fi
864 | TSV_FILE="${NEW_TSV_FILE}"
865 | echo "File renamed to '${sanitized}${default_filename}'."
866 | else
867 | echo "You entered the same prefix."
868 | fi
869 | else
870 | echo "No action taken, the file remains intact."
871 | fi
872 | }
873 |
874 |
875 | delete_file() {
876 | # Delete a file
877 | no_active_file=0
878 | echo "Available files:"
879 | file_options
880 | prefix=""
881 | if [[ ${#tags[@]} -eq 0 ]]; then
882 | new=1
883 | echo "Nothing to delete, create a new file instead."
884 | echo
885 | new_file
886 | return
887 | fi
888 | opt=$(( ${#tags[@]} ))
889 | while [[ ! $REPLY =~ ^[1-${opt}]$ ]]; do
890 | read -p "Choose a file to be deleted [1-${opt}]: " REPLY
891 | done
892 | (( REPLY-- ))
893 | if [[ "${tags[$REPLY]^^}" != "DEFAULT" ]]; then
894 | prefix="${tags[$REPLY]}_"
895 | fi
896 | if [[ -n $REPLY && "${prefix}${default_filename}" == "${defaults["active_file"]}" ]]; then
897 | yes_no "WARNING: Are you sure to delete currently active file '${prefix}${default_filename}'?"
898 | if [[ $user_input == "yes" ]]; then
899 | no_active_file=1
900 | fi
901 | elif [[ -n $REPLY && "${prefix}${default_filename}" != "${defaults["active_file"]}" ]]; then
902 | yes_no "Are you sure to delete the file '${prefix}${default_filename}'?"
903 | fi
904 | if [[ $user_input == "yes" ]]; then
905 | rm "${SCRIPTPATH}/${DATA}/${prefix}${default_filename}"
906 | # Delete if the SETTINGS exists
907 | if [[ -e "${SCRIPTPATH}/${DATA}/${prefix}${default_log}" ]]; then
908 | rm "${SCRIPTPATH}/${DATA}/${prefix}${default_log}"
909 | fi
910 | # Delete if the TSV_FILE exists
911 | if [[ -e "${SCRIPTPATH}/${DATA}/${prefix}${default_tsv}" ]]; then
912 | rm "${SCRIPTPATH}/${DATA}/${prefix}${default_tsv}"
913 | fi
914 | echo "File deleted."
915 | else
916 | echo "No action taken, the file remains intact."
917 | fi
918 | if [[ $user_input == "yes" && $no_active_file -eq 1 ]]; then
919 | echo
920 | select_file
921 | fi
922 | }
923 |
924 |
925 | # Custom select function
926 | custom_select() {
927 | echo -e "\nAvailable actions: "
928 | for i in "${!options[@]}"; do
929 | echo -e " [${yellow}$((i+1))${reset}] ${options[$i]}"
930 | done
931 |
932 | echo
933 | opt=${#options[@]}
934 | while [[ ! $REPLY =~ ^[1-${opt}]$ ]]; do
935 | read -p "Enter choice [1-${opt}]: " REPLY
936 | done
937 | }
938 |
939 |
940 | get_files() {
941 | default_f=$(echo "$([[ -f ${SCRIPTPATH}/${DATA}/${default_filename} && -w ${SCRIPTPATH}/${DATA}/${default_filename} ]] && ls -lih --time-style="+%Y-%m-%d %X" ${SCRIPTPATH}/${DATA}/${default_filename} 2>/dev/null | awk '{print $6, $7, $8}') DEFAULT")
942 | data="${default_f}"
943 | for file in "${SCRIPTPATH}/${DATA}/"*_${default_filename}; do
944 | if [[ -w "$file" ]] && [[ "$file" != "${SCRIPTPATH}/${DATA}/${default_filename}" ]]; then
945 | info=$(ls -lih --time-style="+%Y-%m-%d %X" "$file" | awk '{print $6, $7, $8}')
946 | prefix=$(basename "$file" | awk -v filename="_${default_filename}" '{n = split($0,a,filename); printf "%s", a[1]; for (i = 2; i < n; i++) printf "_%s", a[i]}')
947 | data+=$'\n'"${info} ${prefix}"
948 | fi
949 | done
950 | }
951 |
952 |
953 | # Main menu
954 | base() {
955 | declare -a tags=()
956 | local selected
957 | new=0
958 | echo
959 |
960 | while :
961 | do
962 | unset REPLY FILE
963 | tags=()
964 | get_files
965 | # Process each line of the data
966 | if [[ -z ${data} ]]; then
967 | new=1
968 | echo "No files found, let's create one."
969 | echo
970 | new_file
971 | else
972 | if [[ "${defaults["active_file"]}" == "${default_filename}" ]]; then
973 | selected="DEFAULT"
974 | elif [[ "${defaults["active_file"]}" == "" ]]; then
975 | selected=""
976 | else
977 | selected="${defaults["active_file"]%_$default_filename}"
978 | fi
979 | echo "${data}" | awk -v green="${green}" -v reset="${reset}" -v bullet="${bullet_personal}" -v var="${selected}" '{if ($4 == var) selected=bullet; else selected=" "; printf "%6s %s %s %s %s\n", $1, $2, $3, selected, green $4 reset}'
980 | fi
981 |
982 | # Define options
983 | options=("Create New" "View" "Edit" "Select" "Rename" "Delete" "Import from TSV" "Export to TSV" "Quit")
984 |
985 | # Call the function
986 | custom_select
987 |
988 | # Process user's choice
989 | case $REPLY in
990 | 1)
991 | echo "▸▸▸ Selected: ${options[0]}"
992 | echo
993 | new_file
994 | ;;
995 | 2)
996 | echo "▸▸▸ Selected: ${options[1]}"
997 | echo
998 | view_file
999 | ;;
1000 | 3)
1001 | echo "▸▸▸ Selected: ${options[2]}"
1002 | echo
1003 | edit_file
1004 | ;;
1005 | 4)
1006 | echo "▸▸▸ Selected: ${options[3]}"
1007 | echo
1008 | select_file
1009 | ;;
1010 | 5)
1011 | echo "▸▸▸ Selected: ${options[4]}"
1012 | echo
1013 | rename_file
1014 | ;;
1015 | 6)
1016 | echo "▸▸▸ Selected: ${options[5]}"
1017 | echo
1018 | delete_file
1019 | ;;
1020 | 7)
1021 | echo "▸▸▸ Selected: ${options[6]}"
1022 | echo
1023 | import_from_tsv
1024 | ;;
1025 | 8)
1026 | echo "▸▸▸ Selected: ${options[7]}"
1027 | export_to_tsv
1028 | ;;
1029 | 9)
1030 | echo "Bye."
1031 | echo
1032 | exit
1033 | ;;
1034 | esac
1035 | print_report_line
1036 | echo
1037 | done
1038 | }
1039 |
--------------------------------------------------------------------------------
/src/utils/_view.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Display a simple calendar
4 | dcal() {
5 | # Positioning the current date to arbitrary value
6 | case "${2}" in
7 | $ENFORCE)
8 | # Resolve Overdue Deadlines Mode
9 | test_date="${1}"
10 | enforce_resolve="${2}"
11 | mode=$ENFORCE
12 | ;;
13 | $CUSTOM_RANGE_KEY)
14 | # Calendar Calculator View
15 | start_end_date="${1}"
16 | range_key="${2}"
17 | test_date="${start_end_date%% *}"
18 | mode=$CUSTOM_RANGE_KEY
19 | if [[ $test_date == $TODAY ]]; then
20 | test_date=""
21 | else
22 | MSG['today']="From"
23 | MSG['until_deadline']="until target"
24 | MSG['days_until_deadline']="days ${MSG['until_deadline']}"
25 | fi
26 | end_date="${start_end_date#* }"
27 | ;;
28 | *)
29 | # Just continue
30 | test_date="${1}"
31 | ;;
32 | esac
33 | test_year=""
34 | # Display month without showing the current date
35 | display_month=0
36 | if ! test_year=$(date -d "$test_date" +%Y 2>/dev/null); then
37 | if [[ $test_date =~ ^[0-9]{4}\/[0-9]{2}$ ]]; then
38 | test_date="${test_date}/01"
39 | display_month=1
40 | else
41 | test_date=""
42 | fi
43 | fi
44 |
45 | IFS="/"
46 | if [[ -z "${test_date}" ]]; then
47 | formatted_date=$(date "+%Y/%m/%d/%b/%j/%U/%V/%A/%u/%X/${LOCALE_FMT}")
48 | start_timestamp=$(date -d "12:00 PM" "+%s")
49 | else
50 | local test_ts
51 | formatted_date=$(date -d "${test_date}" "+%Y/%m/%d/%b/%j/%U/%V/%A/%u/%X/${LOCALE_FMT}")
52 | [[ $test_date == *":"* ]] && test_ts=${test_date:0:-6} || test_ts=${test_date}
53 | start_timestamp=$(date -d "${test_ts} 12:00 PM" "+%s")
54 | fi
55 |
56 | # Use the read command to split the output into separate variables
57 | read year month day month_name day_of_year current_week_ansi current_week_iso day_name start_dow current_time current_date_formatted <<< "$formatted_date"
58 |
59 | output2=$(date -d "${year}/12/28" "+%U/%V")
60 | read total_weeks_ansi total_weeks_iso <<< "$output2"
61 | unset IFS
62 |
63 | current_date="${year}/${month}/${day}"
64 | current_date_dd="${current_date////-}"
65 | first_weekday=$(locale -k LC_TIME | grep ^first_weekday | cut -d= -f2 | tr -d '"')
66 |
67 | if [[ $display_month -ne 1 ]]; then
68 | if [[ -z ${oha_last_imported} ]] || [[ ${oha_last_imported} == "" ]] || [[ ${oha_last_imported:0:4} < $year ]] || [[ ${current_date_dd} > "${year}-08-31" && ${oha_last_imported} < "${year}-08-31" ]]; then
69 | source ${SCRIPTPATH}/${API}/oha.sh
70 | oha
71 | update_api_date_log
72 | if [[ ${oha_country_iso^^} != "X" ]]; then
73 | sort_input
74 | fi
75 | fi
76 |
77 | if [[ $gca_skip -ne 1 ]]; then
78 | gca_init
79 | fi
80 | fi
81 |
82 | # Determine the scenario of running the function
83 | # If the $CUSTOM_RANGE_KEY is set, it means we're just calculating custom date range
84 | if [[ ${2} == $CUSTOM_RANGE_KEY ]]; then
85 | # Mode: Calendar Calculator View
86 | # read end_timestamp end_date_input end_date_formatted workdays days end_dow description <<< $(get_next_deadline "${current_date}" "${end_date}")
87 | count_group_events "${current_date}" "${end_date}"
88 | if [[ "${month_name^^}" != "${end_date_month^^}" ]]; then
89 | month_name="${month_name^^} - ${end_date_month^^}"
90 | fi
91 | else
92 | # read end_timestamp end_date_input end_date_formatted workdays days end_dow description <<< $(get_next_deadline)
93 | get_next_deadline
94 | fi
95 |
96 | # Remove leading zeros from the variables
97 | month=${month#0}
98 | day=${day#0}
99 |
100 | # Get the total number of days in the current year (leap year detection)
101 | if [ "$(date -d "${year}-02-29" +%Y-%m-%d 2>/dev/null)" = "${year}-02-29" ]; then
102 | days=366
103 | else
104 | days=365
105 | fi
106 |
107 | if [ $first_weekday -eq 2 ]; then
108 | total_weeks=${total_weeks_iso}
109 | if [[ "${month}" == "1" && "${day}" -le 3 && "$(date -d "${year}/01/01" "+%V")" != "01" ]]; then
110 | current_week=0
111 | elif [[ "${month}" == "12" && "${current_week_iso}" == "01" ]]; then
112 | current_week=$((total_weeks + 1))
113 | else
114 | current_week=${current_week_iso}
115 | fi
116 | # Check if December 31 is in the first week of the next year and adjust the week number accordingly
117 | if [[ "$(date -d "${year}/12/31" "+%V")" == "01" ]]; then
118 | total_weeks=$((total_weeks + 1))
119 | fi
120 | else
121 | current_week=${current_week_ansi}
122 | total_weeks=${total_weeks_ansi}
123 | fi
124 | # Get the progress of the current year (values with leading zeros in bash are treated like octal numbers)
125 | percent=$((100 * $((10#$day_of_year)) / $days))
126 |
127 | if [[ $display_month -eq 0 ]]; then
128 | print_month_line
129 | # Print the required information
130 | printf "${color_header}${MSG['progress']}: %s%% ${MSG['day']}: %s/%03d ${MSG['week']}: %s/%02d ${MSG['today']}: %s, %s ${MSG['time']}: %s${reset}\n" "$percent" $day_of_year $days $current_week $total_weeks $day_name "$current_date_formatted" "$current_time"
131 | fi
132 |
133 | passed_due_date=0
134 | start_date=$current_date
135 | end_date=$end_date_input
136 |
137 | # First day of the month (timestamp)
138 | s=$((start_timestamp - (10#$day-1) * 86400))
139 |
140 | # Check if the start date is before the end date
141 | if [[ $start_timestamp-$end_date_timestamp -gt 86400 ]]; then
142 | passed_due_date=1
143 | start=$start_timestamp
144 | start_timestamp=$((end_date_timestamp+86400))
145 | end_date_timestamp=$start
146 | start_date=$end_date_input
147 | end_date=$current_date
148 | fi
149 |
150 | # Checking a proper use of singular vs. plural: day(s)
151 | sp=${MSG['day_plural']}
152 | if [[ $total_days -eq 1 ]]; then
153 | sp=${MSG['day_singular']}
154 | fi
155 |
156 | if [[ $display_month -eq 0 ]]; then
157 | if [[ $passed_due_date -eq 0 ]]; then
158 | if [[ "$workdays" -ne "$total_days" ]]; then
159 | if [[ "$end_date_formatted" == *"New Year"* ]]; then
160 | printf "%s ${MSG['days_until_the']} %s · %s ${MSG['workdays_left']}\n" $total_days "$end_date_formatted" $workdays
161 | else
162 | # Capture the output of printf into a variable
163 | output=$(printf "%s ${MSG['days_until_deadline']} (%s) · %s ${MSG['workdays_left']} · \n" $total_days "$end_date_formatted" $workdays)
164 |
165 | # Measure the visible length of the output
166 | length=$(visible_length "$output")
167 | trunc_desc "${description}"
168 |
169 | # Print the output and its length
170 | printf "%s ${MSG['days_until_deadline']} (%s) · %s ${MSG['workdays_left']} · %s\n" $total_days "$end_date_formatted" $workdays "$desc_truncated"
171 | fi
172 | else
173 | if [[ "$end_date_formatted" == *"New Year"* ]]; then
174 | printf "%s %s ${MSG['until_the']} %s · ${MSG['happy_new_year']}\n" $workdays $sp "$end_date_formatted"
175 | else
176 | # Capture the output of printf into a variable
177 | output=$(printf "%s %s ${MSG['until_deadline']} (%s) · ${MSG['soon']} · \n" $workdays $sp "$end_date_formatted")
178 |
179 | # Measure the visible length of the output
180 | length=$(visible_length "$output")
181 | trunc_desc "${description}"
182 |
183 | # Print the output and its length
184 | printf "%s %s ${MSG['until_deadline']} (%s) · ${MSG['soon']} · %s\n" $workdays $sp "$end_date_formatted" "$desc_truncated"
185 | fi
186 | fi
187 | else
188 | # Capture the output of printf into a variable
189 | output=$(printf "${alert}${MSG['overdue']}: %s${reset} · \n" "$total_days")
190 |
191 | # Measure the visible length of the output
192 | length=$(visible_length "$output")
193 | trunc_desc "${description}"
194 |
195 | # Print the output and its length
196 | printf "${alert}${MSG['overdue']}: %s${reset} · %s\n" "$total_days" "$desc_truncated"
197 | fi
198 | fi
199 |
200 | check_max_width
201 |
202 | # If we've reached to this point and have the $CUSTOM_RANGE_KEY set, terminate the execution
203 | if [[ ${2} == $CUSTOM_RANGE_KEY ]]; then
204 | # Mode: Calendar Calculator View
205 | view_report
206 | echo
207 | exit 0
208 | fi
209 |
210 | # Split end_date into year, month, and day
211 | IFS="/" read end_year end_month end_day <<< "$end_date"
212 |
213 | # Add leading zeros to month and day if they are single digits
214 | printf -v end_month '%02d' "$((10#$end_month))"
215 | printf -v end_day '%02d' "$((10#$end_day))"
216 |
217 | # Combine year, month, and day into the new end_date
218 | end_date="${end_year}/${end_month}/${end_day}"
219 |
220 | # Horizontal line
221 | print_line
222 |
223 | printf -v month_zero '%02d' "$((10#$month))"
224 | printf -v day_zero '%02d' "$((10#$day))"
225 |
226 | l0= l1= l2=
227 |
228 | IFS=";"
229 |
230 | # Declare the array "months" (locale names)
231 | declare -a months
232 | months=($(locale -k LC_TIME | grep ^abmon | cut -d= -f2 | tr -d '"'))
233 | unset IFS
234 |
235 | # Get the 2-letter abbreviations for Saturday and Sunday
236 | sat=$(LC_TIME=C date -dSaturday +%a)
237 | sun=$(LC_TIME=C date -dSunday +%a)
238 |
239 | # Combine the abbreviations
240 | weekend_days="$sat$sun"
241 |
242 | last_date=""
243 | last_day=""
244 | multi_event_day=""
245 | # old_day="$day"
246 | # old_end_date="$end_date"
247 | # Read the deadlines into an array
248 | # mapfile -t deadlines < <(statuses_in_month)
249 | local date_pattern="^$year/$month_zero/"
250 | local monthly_sorted_lines="$(echo "${sorted_lines}" | grep "${date_pattern}")"
251 | mapfile -t deadlines <<<"${monthly_sorted_lines}"
252 |
253 | if [[ ${#defaults[@]} -eq 0 ]]; then
254 | echo "Internal error: JSON file can not be parsed."
255 | exit 1
256 | fi
257 |
258 | # s - first day of the month (timestamp)
259 | # a - name of a day
260 | # d - date
261 | # m - month
262 | while
263 | for field in a d m; do printf -v "$field" "%(%-$field)T" "$s"; done
264 | ((month == m))
265 | do
266 | if [[ $d -lt 13 ]]; then
267 | if [[ $d -lt $month ]]; then
268 | color="${color_past_months}"
269 | elif [[ $d -gt $month ]]; then
270 | color="${color_future_dates}"
271 | else
272 | color="${color_current_month}"
273 | fi
274 | printf -v l0 "%s${color}%-8s${reset}" "$l0" "${months[$d-1]}"
275 | fi
276 |
277 | (( ${#a} > 2 )) && a="${a:0:2}"
278 | printf -v d_zero '%02d' "$((10#$d))"
279 | # If the day and date have already been processed due to DST, skip the rest of the loop
280 | if [[ "$last_day" == "$a" && "$last_date" == "$d" ]]; then
281 | ((s += 86400))
282 | continue
283 | fi
284 |
285 | # DEBUG: Show current iteration values
286 | [ "${DEBUG:-0}" -eq 1 ] && echo "DEBUG: d=$d, day=$day, d_zero=$d_zero, a=$a, s=$s"
287 |
288 | if [[ $display_month -eq 1 ]]; then
289 | day=0
290 | end_date="1970/01/01"
291 | fi
292 | if [[ 10#$d -lt 10#$day ]]; then
293 | color="${color_past_dates}"
294 | else
295 | # Call extract_status for every day to detect deadlines
296 | extract_status
297 |
298 | # DEBUG: output the values after running extract_status
299 | [ "${DEBUG:-0}" -eq 1 ] && echo "DEBUG: end_date=$end_date, status=$status, d_zero=$d_zero"
300 |
301 | if [[ -n $end_date && "$end_date" == "$year/$month_zero/$d_zero" ]]; then
302 | # A calendar entry exists for the current day – select color based on its status.
303 | if [[ "$weekend_days" == *"$a"* ]]; then
304 | if [[ $status == "1" && ${defaults["categories[1][show]"]} -eq 1 ]]; then
305 | [ "${DEBUG:-0}" -eq 1 ] && echo "DEBUG: In weekend branch for deadline on $d_zero ($a)"
306 | color=$(get_bg_color "${color_deadline_cal}")
307 | elif [[ $status == "5" && ${defaults["categories[5][show]"]} -eq 1 ]]; then
308 | [ "${DEBUG:-0}" -eq 1 ] && echo "DEBUG: In weekend branch for public holiday on $d_zero ($a)"
309 | color="${color_public_holiday_cal}"
310 | multi_event_day="$d_zero"
311 | elif [[ $status == "2" && ${defaults["categories[2][show]"]} -eq 1 ]]; then
312 | [ "${DEBUG:-0}" -eq 1 ] && echo "DEBUG: In weekend branch for work on $d_zero ($a)"
313 | color=$(get_bg_color "${color_work_cal}")
314 | elif [[ $status == "3" && ${defaults["categories[3][show]"]} -eq 1 ]]; then
315 | [ "${DEBUG:-0}" -eq 1 ] && echo "DEBUG: In weekend branch for personal on $d_zero ($a)"
316 | color=$(get_bg_color "${color_personal_cal}")
317 | elif [[ $status == "4" && ${defaults["categories[4][show]"]} -eq 1 ]]; then
318 | [ "${DEBUG:-0}" -eq 1 ] && echo "DEBUG: In weekend branch for birthday on $d_zero ($a)"
319 | color=$(get_bg_color "${color_birthday_cal}")
320 | elif [[ $status == "0" && ${defaults["categories[0][show]"]} -eq 1 ]]; then
321 | [ "${DEBUG:-0}" -eq 1 ] && echo "DEBUG: In weekend branch for resolved deadline on $d_zero ($a)"
322 | color=$(get_bg_color "${color_resolved_cal}")
323 | else
324 | [ "${DEBUG:-0}" -eq 1 ] && echo "DEBUG: In weekend branch for regular weekend on $d_zero ($a)"
325 | color="${color_weekends}"
326 | fi
327 | else
328 | if [[ $status == "1" && ${defaults["categories[1][show]"]} -eq 1 ]]; then
329 | color="${color_deadline_cal}"
330 | elif [[ $status == "5" && ${defaults["categories[5][show]"]} -eq 1 ]]; then
331 | color="${color_public_holiday_cal}"
332 | elif [[ $status == "2" && ${defaults["categories[2][show]"]} -eq 1 ]]; then
333 | color="${color_work_cal}"
334 | elif [[ $status == "3" && ${defaults["categories[3][show]"]} -eq 1 ]]; then
335 | color="${color_personal_cal}"
336 | elif [[ $status == "4" && ${defaults["categories[4][show]"]} -eq 1 ]]; then
337 | color="${color_birthday_cal}"
338 | elif [[ $status == "6" && ${defaults["categories[6][show]"]} -eq 1 ]]; then
339 | color="${color_vacation_cal}"
340 | elif [[ $status == "7" && ${defaults["categories[7][show]"]} -eq 1 ]]; then
341 | color="${color_sick_leave_cal}"
342 | elif [[ $status == "8" && ${defaults["categories[8][show]"]} -eq 1 ]]; then
343 | if [[ $school -eq 1 ]]; then
344 | color="${color_school_holiday_cal}"
345 | else
346 | color="${color_school_holiday_cal_parent}"
347 | fi
348 | elif [[ $status == "0" && ${defaults["categories[0][show]"]} -eq 1 ]]; then
349 | color="${color_resolved_cal}"
350 | else
351 | # If no status is matched, default to future date color
352 | color=""
353 | fi
354 | fi
355 | else
356 | # No calendar entries for this date.
357 | if [[ -z $color ]]; then
358 | # For static views (previous month), assign weekend color if the day is Saturday or Sunday,
359 | # otherwise use the future date color.
360 | if [[ "$weekend_days" == *"$a"* ]]; then
361 | color="${color_weekends}"
362 | fi
363 | fi
364 | fi
365 | if [[ $display_month -ne 1 ]]; then
366 | # For the current month, check whether this day is today.
367 | [ "${DEBUG:-0}" -eq 1 ] && echo "DEBUG: Testing today..."
368 | if [[ "$year/$month_zero/$day_zero" == "$year/$month_zero/$d_zero" ]]; then
369 | [ "${DEBUG:-0}" -eq 1 ] && echo "DEBUG: [$year/$month_zero/$d_zero] Today found!"
370 | color="${color_today}"
371 | fi
372 | fi
373 | fi
374 | printf -v l1 "%s${color}%-2s${reset} " "$l1" "$a"
375 | printf -v l2 "%s${color}%+2s${reset} " "$l2" "$d"
376 | ((s += 86400))
377 | last_day="$a"
378 | last_date="$d"
379 | done
380 |
381 | if [[ $display_month -eq 1 ]]; then
382 | # Mode: Static Calendar View
383 | view_calendar
384 | exit 0
385 | fi
386 |
387 | # Mode: Dynamic Calendar View (DEFAULT)
388 | # Read the overdues into an array
389 | mapfile -t overdues < <(get_overdue_deadlines)
390 | # If the INPUT_FILE hasn't been touched for more than 24h, ask the user about overdue deadlines
391 | given_time="${year}/${month_zero}/${day_zero} $current_time"
392 | given_time_in_seconds=$(date -d "$given_time" +%s)
393 |
394 | # Check if the last scheduled cleanup date exists
395 | if [[ -n $last_scheduled_date ]]; then
396 | # Calculate seconds in DEFAULT_CLEANUP_FREQUENCY months
397 | seconds_in_months=$((DEFAULT_CLEANUP_FREQUENCY * 30 * 24 * 60 * 60))
398 |
399 | # Calculate default_cleanup_date
400 | if (( $seconds_in_months == 0 )); then
401 | # Setting: never perform an automatic cleanup
402 | default_cleanup_date=$((start_timestamp + 60))
403 | else
404 | default_cleanup_date=$((last_scheduled_date + seconds_in_months))
405 | fi
406 |
407 | view_calendar
408 |
409 | if [[ $enforce_resolve == $ENFORCE ]] || [[ $enforce_resolve != $ENFORCE && $last_overdue_date -le $(( given_time_in_seconds-24*60*60 )) && $display_month -ne 1 ]]; then
410 | process_overdues
411 | cleanup_inactive_pids
412 | fi
413 | else
414 | view_calendar
415 | # The last execution date for scheduled backup doesn't exist, so we assume this is the first run
416 | last_scheduled_date=0
417 | # Initiate additional checks
418 | process_overdues
419 | cleanup_inactive_pids
420 | fi
421 |
422 | # Check if the current date (start_timestamp) is later than the default_cleanup_date
423 | if [[ $start_timestamp -gt $default_cleanup_date ]]; then
424 | expired_lines
425 | # If expired_lines found any expired events stored in $lines
426 | if [[ -n $lines ]]; then
427 | scheduled_cleanup
428 | fi
429 | fi
430 | }
431 |
432 |
433 | view_legend() {
434 | # Check if legend is 1
435 | if [[ $legend -eq 1 ]]; then
436 | print_legend_line
437 | print_legend | sed 's/^/ /'
438 | else
439 | if [[ -n $verbose ]]; then
440 | echo
441 | fi
442 | fi
443 | }
444 |
445 |
446 | view_calendar() {
447 | # Print the calendar
448 | n=$(( ($MAX_LINE_LENGTH - $last_date*3)/$last_date ))
449 | m=$(( ($MAX_LINE_LENGTH - (12*8-4))/12 )); (( m > 2 )) && m=$((m-3));
450 | spaces=$(printf "%${n}s" " ")
451 | spaces_m=$(printf "%${m}s")
452 | # echo "$l0" | cat -v
453 |
454 | # Replace all occurrences of "\033[0m " with "\033[0m $spaces" in $l1
455 | l0=$(echo -e "$l0" | sed "s/$(echo -e '\033')\[0m/$(echo -e '\033')\[0m$spaces_m/g")
456 | l1=$(echo -e "$l1" | sed "s/$(echo -e '\033')\[0m /$(echo -e '\033')\[0m$spaces/g")
457 | l2=$(echo -e "$l2" | sed "s/$(echo -e '\033')\[0m /$(echo -e '\033')\[0m$spaces/g")
458 |
459 | # Remove all trailing spaces
460 | l0=$(echo "$l0" | sed 's/[ \t]*$//')
461 | l1=$(echo "$l1" | sed 's/[ \t]*$//')
462 | l2=$(echo "$l2" | sed 's/[ \t]*$//')
463 |
464 | # Print the results
465 | printf '%s\n%s\n%s\n' "$l0" "$l1" "$l2"
466 |
467 | if [[ $verbose -eq 1 ]]; then
468 | view_monthly_events_details
469 | view_legend
470 | else
471 | echo
472 | fi
473 | }
474 |
475 |
476 | print_line() {
477 | # Straight line
478 | local total_cols
479 | local highlight_cols
480 | if [[ $display_month -eq 1 ]]; then
481 | print_month_line
482 | else
483 | total_cols=$(tput cols)
484 | highlight_cols=$((total_cols * $percent / 100)) # Calculate the number of columns to highlight
485 | echo -ne "$color_line_highlight"
486 | printf '%.s─' $(seq 1 "$highlight_cols")
487 | echo -ne "$color_line"
488 | [[ $highlight_cols -lt $total_cols ]] && printf '%.s─' $(seq "$((highlight_cols + 1))" "$(( total_cols + (highlight_cols > 0 ? 0 : -1) ))")
489 | echo -e "$reset"
490 | fi
491 | }
492 |
493 |
494 | print_report_line() {
495 | # Straight line
496 | echo -ne "$color_line$(spaces $(( $leading_spaces - 2 )))"
497 | printf '%.s─' $(seq 1 $(( ${MAX_LINE_LENGTH} - 2*$leading_spaces + 4 )))
498 | echo -e "$reset"
499 | }
500 |
501 |
502 | print_month_line() {
503 | local len_month=${#month_name}
504 | local total_cols=$(tput cols)
505 | local max_total_cols=$((total_cols - len_month - 1))
506 | local highlight_cols=$((total_cols * $percent / 100)) # Calculate the number of columns to highlight
507 |
508 | [[ $highlight_cols -gt $max_total_cols ]] && highlight_cols=${max_total_cols}
509 |
510 | # Print the highlighted part
511 | echo -ne "$color_line_highlight"
512 | printf '%.s─' $(seq 1 "$highlight_cols")
513 |
514 | # Print the remaining part in the original color
515 | echo -ne "$color_line"
516 | [[ $highlight_cols -lt $(( max_total_cols )) ]] && printf '%.s─' $(seq "$((highlight_cols + 1))" "$((max_total_cols - 1))")
517 |
518 | # Print the month name
519 | echo -e "${reset} ${month_name^^}"
520 | }
521 |
522 |
523 | print_legend_line() {
524 | # Straight line
525 | echo -ne "$color_line"
526 | printf '%.s─' $(seq 1 $(( $(tput cols) - 7 )))
527 | echo -ne " ᴸᴱᴳᴱᴺᴰ"
528 | echo -e "$reset"
529 | }
530 |
531 |
532 | print_legend() {
533 | # Parse the JSON data into an array using jq only once
534 | # parse_json
535 | declare -a entries
536 | # Calculate the number of categories
537 | for ((i=0; i<=${num_categories}; i++)); do
538 | name=${defaults["categories[$i][name]"]}
539 | # Skip if no category name is returned
540 | if [[ -n $name ]]; then
541 | if [[ "${i}" == "8" && ${school} -ne 1 ]]; then
542 | color="color_school_holiday_cal_parent"
543 | else
544 | color=${defaults["categories[$i][color]"]}
545 | fi
546 | bullet=${defaults["categories[$i][bullet]"]}
547 | show=${defaults["categories[$i][show]"]}
548 | # Skip category 0
549 | if [[ $i != 0 ]]; then
550 | entries+=("$i" "$name" "$color" "$bullet" "$show")
551 | fi
552 | fi
553 | done
554 |
555 | # Calculate the available space for each item
556 | item_space=$(( MAX_LINE_LENGTH / 4))
557 | # Total number of category items
558 | total_items=$((${#entries[@]} / 5))
559 | # Maximum number of rows
560 | total_rows=$(( ${total_items} / 4 ))
561 |
562 | # Prepare a variable to hold the output
563 | output=""
564 |
565 | # Initialize an array to store the maximum length for each column
566 | max_lengths=(-1 -1 -1 -1)
567 |
568 | # Iterate over each row
569 | for ((row=0; row<${total_rows}; row++)); do
570 | # Iterate over each column
571 | for ((col=0; col<4; col++)); do
572 | # Calculate the index of the name in the entries array
573 | index=$((row * 20 + col * 5 + 1))
574 | # Check if the index exists in the entries array
575 | if [[ -v entries[index] ]]; then
576 | # Get the name
577 | name=${entries[index]}
578 | # Get the length of the name
579 | length=${#name}
580 | # Update the maximum length for the column if necessary
581 | if (( length > max_lengths[col] )); then
582 | max_lengths[col]=$length
583 | fi
584 | fi
585 | done
586 | done
587 |
588 | # Calculate the sum of all max_lengths values
589 | sum_max_lengths=$(IFS=+; echo "$((${max_lengths[*]}))")
590 | if [[ $sum_max_lengths < $MAX_LINE_LENGTH ]]; then
591 | single_space=$(( (MAX_LINE_LENGTH-sum_max_lengths)/3 ))
592 | fi
593 |
594 | # Prepare the names and keys in two lines and four columns
595 | for ((i=0; i<${#entries[@]}; i+=5)); do
596 | # Get the color and bullet using variable indirection
597 | name=${entries[i+1]}
598 | color=${!entries[i+2]}
599 | bullet=${!entries[i+3]}
600 | show=${entries[i+4]}
601 | # Calculate the number of spaces needed to reach item_space
602 | bullet_visible=$(visible_length "${bullet}")
603 |
604 | # Truncate the name if necessary and append an ellipsis
605 | if [[ -z ${single_space} ]]; then
606 | if (( ${#name} + ${#entries[i]} + bullet_visible + 1 > item_space )); then
607 | name=${name:0:$((item_space - ${#name} - ${#entries[i]} - bullet_visible - 1))}"…"
608 | fi
609 | fi
610 | crossed=""
611 | if [[ $show -ne 1 ]]; then
612 | crossed="${effect_crossed_out}"
613 | color="${color_resolved}"
614 | fi
615 | # Add the color, bullet, name, key, and reset to the output
616 | line="${color}${bullet} ${crossed}${name}${reset}${color}$(tiny_text ${entries[i]})${reset}"
617 | output+="$line"
618 | # Add a new line after the fourth column
619 | if (( (i / 5 + 1) % 4 == 0 )); then
620 | output+="\n"
621 | else
622 | if [[ -n ${single_space} ]]; then
623 | cols=$(( (i/5)%4 ))
624 | spaces_needed=$((${max_lengths[cols]} + ${single_space} - ${#name} - ${#entries[i]} - bullet_visible - 1))
625 | # Add the spaces to the output
626 | else
627 | spaces_needed=$((item_space - ${#name} - ${#entries[i]} - bullet_visible - 1))
628 | # Add the spaces to the output
629 | fi
630 | output+=$(printf "%${spaces_needed}s")
631 | fi
632 | done
633 |
634 | # Print the output
635 | echo -e "${output}"
636 | }
637 |
638 |
639 | view_report() {
640 | local categories=()
641 | local numbers_workday=()
642 | local numbers_weekend=()
643 | local count_workday_events=0
644 | local count_weekend_events=0
645 |
646 | for ((i=0; i<=${num_categories}; i++)); do
647 | name=${defaults["categories[$i][name]"]}
648 | # Skip if no category name is returned
649 | if [[ -n $name ]]; then
650 | color=${defaults["categories[$i][color]"]}
651 | if [[ $i -eq 8 && $school -ne 1 ]]; then
652 | categories+=("${color_school_holiday_cal_parent}${name}${reset}")
653 | numbers_workday+=("${color_school_holiday_cal_parent}$(add_thousand_separators ${report_workday[$i]:-0})${reset}")
654 | numbers_weekend+=("${color_school_holiday_cal_parent}$(add_thousand_separators ${report_weekend[$i]:-0})${reset}")
655 | continue
656 | fi
657 | categories+=("${!color}${name}${reset}")
658 | numbers_workday+=("${!color}$(add_thousand_separators ${report_workday[$i]:-0})${reset}")
659 | numbers_weekend+=("${!color}$(add_thousand_separators ${report_weekend[$i]:-0})${reset}")
660 | fi
661 | done
662 | # Add an element to the start of the index array
663 | categories+=("No Events")
664 | numbers_workday+=("$(add_thousand_separators $(( ${workdays:-0} + ${non_working_days:-0} - ${weekdays_with_events:-0} )))")
665 | numbers_weekend+=("$(add_thousand_separators $(( ${weekends:-0} - ${weekends_with_events:-0} )))")
666 | categories+=("Total")
667 | numbers_workday+=("$(add_thousand_separators $(( ${workdays:-0} + ${non_working_days:-0} )))")
668 | numbers_weekend+=("$(add_thousand_separators ${weekends:-0})")
669 | categories+=("")
670 | numbers_workday+=("On-duty")
671 | numbers_weekend+=("Off-duty")
672 | categories+=("Weekdays")
673 | numbers_workday+=("$(add_thousand_separators ${workdays:-0})")
674 | numbers_weekend+=("$(add_thousand_separators ${non_working_days:-0})")
675 | categories+=("${color_weekends}Weekends${reset}")
676 | numbers_workday+=("${color_weekends}$(add_thousand_separators ${working_days:-0})${reset}")
677 | numbers_weekend+=("${color_weekends}$(add_thousand_separators $(( ${weekends:-0} - ${working_days:-0} )))${reset}")
678 | categories+=("CUMULATIVE")
679 | numbers_workday+=("$(add_thousand_separators $(( ${working_days:-0} + ${workdays:-0} )))")
680 | numbers_weekend+=("$(add_thousand_separators $(( ${weekends:-0} - ${working_days:-0} + ${non_working_days:-0} )))")
681 |
682 | # Define headers
683 | header_text="Event Category"
684 | header_num1="Weekdays"
685 | header_num2="Weekends"
686 |
687 |
688 | # Find the length of the longest string in each column
689 | maxlen_text=${#header_text}
690 | maxlen_num1=$(( ${#header_num1}+var ))
691 | maxlen_num2=$(( ${#header_num2}+var ))
692 |
693 | # Calculate the maximum length of the items in each column, including the headers
694 | max_length_column1=$(max_length "${header_text}" "${categories[@]}")
695 | max_length_column2=$(max_length "${header_num1}" "${numbers_workday[@]}")
696 | max_length_column3=$(max_length "${header_num2}" "${numbers_weekend[@]}")
697 |
698 | # Calculate the space between columns
699 | leading_spaces=8
700 | local max_length=$((MAX_LINE_LENGTH < 92 ? MAX_LINE_LENGTH-leading_spaces+4 : 92-leading_spaces+4))
701 |
702 | space=$(( (max_length - leading_spaces -max_length_column1 - max_length_column2 - max_length_column3) / 2 ))
703 |
704 | echo
705 | echo
706 | # Print the header
707 | echo -e "$(spaces $leading_spaces)${header_text}$(spaces $((space + max_length_column1 - $(strip_escape_codes "${header_text}" | wc -m))))${header_num1}$(spaces $((space + max_length_column2 - $(strip_escape_codes "${header_num1}" | wc -m))))${header_num2}"
708 |
709 | # Print the elements of the arrays
710 | for ((i=0; i<${#categories[@]}; i++)); do
711 | # Calculate the number of spaces needed to align the columns
712 | spaces1=$(( space + max_length_column1 - $(strip_escape_codes "${categories[$i]}" | wc -m) + max_length_column2 - $(strip_escape_codes "${numbers_workday[$i]}" | wc -m )))
713 | spaces2=$((max_length_column3 - $(strip_escape_codes "${numbers_weekend[$i]}" | wc -m) + space))
714 |
715 | if [[ $i -eq 0 || $i -eq $((${#categories[@]}-5)) || $i -eq $((${#categories[@]}-3)) || $i -eq $((${#categories[@]}-1)) ]]; then
716 | print_report_line
717 | elif [[ $i -eq $((${#categories[@]}-4)) ]]; then
718 | echo
719 | echo
720 | fi
721 | # Print the items with the calculated spaces
722 | echo -e "$(spaces $leading_spaces)${categories[$i]}$(spaces $spaces1)${numbers_workday[$i]}$(spaces $spaces2)${numbers_weekend[$i]}"
723 | done
724 | echo
725 | }
726 |
727 |
728 | # Prints all the different categories of events
729 | view_categories() {
730 | # Calculate the number of categories
731 | for ((i=0; i<=${num_categories}; i++)); do
732 | name=${defaults["categories[$i][name]"]}
733 | # Skip if no category name is returned
734 | if [[ -n $name ]]; then
735 | color=${defaults["categories[$i][color]"]}
736 | bullet=${defaults["categories[$i][bullet]"]}
737 | show=${defaults["categories[$i][show]"]}
738 | # Skip category 0
739 | if [[ $i != 0 ]]; then
740 | echo " $i: $name"
741 | fi
742 | fi
743 | done
744 | echo
745 | }
746 |
747 |
748 | view_monthly_events_details() {
749 | # Get all events for the given month
750 | local lines=$(events_in_month)
751 | local date
752 | local status
753 | local description
754 |
755 | # Split the lines into two arrays based on the date
756 | local first_half=()
757 | local second_half=()
758 |
759 | # Variables to track the start of the week
760 | local week_start=$(date "+%u")
761 |
762 | # Needed in 'validate_reminder' (inside the while loop)
763 | current_date="${year}/${month_zero}/${day_zero}"
764 | next_date=$(date -d "+1 day" "+%Y/%m/%d")
765 | current_datetime=$(date +%s)
766 |
767 | # Define description length
768 | desc_length=$(( MAX_LINE_LENGTH/2-9 ))
769 |
770 | # Parse the JSON file into an associative array
771 | declare -A show_values
772 | # while IFS=$'\t' read -r key show; do
773 | # show_values[$key]=$show
774 | # done < <(jq -r '.categories | to_entries[] | [.key, .value.show] | @tsv' $SETTINGS)
775 |
776 | prev_week_number=-1
777 | while IFS= read -r line; do
778 |
779 | # Check if there's any data
780 | if [[ -z $line ]]; then
781 | echo
782 | continue
783 | fi
784 |
785 | # Extract the date and status from the line
786 | local date=${line:0:10}
787 | local date_y=${line:0:4}
788 | local date_m=$((10#${line:5:2}))
789 | local date_d=$((10#${line:8:2}))
790 | local status=${line:11:1}
791 | local description=${line:13}
792 | local show=${defaults["categories[$status][show]"]}
793 |
794 | # Check if the date is valid
795 | if [[ -z $line || -z $date || -z $status || -z $description ]] || [[ ! $date =~ ${date_regex} ]]; then
796 | echo
797 | continue
798 | fi
799 |
800 | # Check if the event is today or tomorrow and has a valid time at the start of the description
801 | [[ $display_month -ne 1 ]] && validate_reminder "${date}" "$status" "${description}"
802 |
803 | if [[ ${show} -eq 1 ]]; then
804 | # Check if the date is in the first or second half of the month
805 | if (( ${date_d} <= 15 )); then
806 | # Check if a new week has started
807 | # week_number=10#$(date -d "$date" "+%V")
808 |
809 | # Calculate the week number (refactored)
810 | week_number=$(get_week_number $date_d)
811 |
812 | if (( week_number > prev_week_number )); then
813 | first_half+=("")
814 | prev_week_number=$week_number
815 | fi
816 | if [[ -n $REMINDER_DESC ]]; then
817 | line="${line:0:13}${REMINDER_DESC}"
818 | unset REMINDER_DESC
819 | fi
820 | first_half+=("$line")
821 | else
822 | # Check if a new week has started
823 | # week_number=10#$(date -d "$date" "+%V")
824 |
825 | # Calculate the week number (refactored)
826 | week_number=$(get_week_number $date_d)
827 |
828 | if (( week_number > prev_week_number )); then
829 | second_half+=("")
830 | prev_week_number=$week_number
831 | fi
832 | if [[ -n $REMINDER_DESC ]]; then
833 | line="${line:0:13}${REMINDER_DESC}"
834 | unset REMINDER_DESC
835 | fi
836 | second_half+=("$line")
837 | fi
838 | fi
839 | done <<< "$(echo -e "$lines")"
840 |
841 | # Trim leading and trailing new lines from first_half and second_half
842 | while [[ ${first_half[0]} == "" && ${#first_half[@]} -gt 1 ]]; do
843 | first_half=("${first_half[@]:1}")
844 | done
845 | while [[ ${#first_half[@]} -gt 1 && ${first_half[-1]} == "" ]]; do
846 | unset 'first_half[${#first_half[@]}-1]'
847 | done
848 | while [[ ${second_half[0]} == "" && ${#second_half[@]} -gt 1 ]]; do
849 | second_half=("${second_half[@]:1}")
850 | done
851 | while [[ ${#second_half[@]} -gt 1 && ${second_half[-1]} == "" ]]; do
852 | unset 'second_half[${#second_half[@]}-1]'
853 | done
854 | # Calculate the number of lines in each column
855 | local num_lines=$(( (${#first_half[@]} > ${#second_half[@]} ? ${#first_half[@]} : ${#second_half[@]}) ))
856 |
857 | local description
858 | local day
859 | local bullet
860 |
861 | # Print the lines in two columns
862 | for (( i=0; i<$num_lines; i++ )); do
863 | # Get the line for the current row in each column
864 | local first_line=${first_half[$i]% #gc}
865 | first_line=${first_line% #oh}
866 | first_line=${first_line:-""}
867 | local second_line=${second_half[$i]% #gc}
868 | second_line=${second_line% #oh}
869 | second_line=${second_line:-""}
870 |
871 | # Inject ANSI codes into first_line and second_line
872 | if [[ -n "$first_line" ]]; then
873 | description=${first_line:13}
874 | # Truncate the lines if they are too long
875 | if (( ${#description} > $desc_length )); then
876 | if [[ $description == *"🔔 "* ]]; then
877 | description="${description:0:$(( $desc_length-2 ))}…"
878 | else
879 | description="${description:0:$(( $desc_length-1 ))}…"
880 | fi
881 | fi
882 | day=${first_line:8:2}
883 | # Read the output of get_bullet into an array
884 | mapfile -t bullet < <(get_bullet ${first_line:0:10} ${first_line:11:1})
885 | if (( ${bullet[2]} == 1 )); then
886 | color_title="${bullet[1]}"
887 | else
888 | color_title="${reset}"
889 | fi
890 | if [[ -z ${bullet[3]} ]]; then
891 | color_date="${color_title}"
892 | else
893 | color_date="${bullet[3]}"
894 | fi
895 | first_line=" ${bullet[0]} ${color_line}[${reset}${color_date}$day${reset}${color_line}] ${color_title}${description}${reset}"
896 | fi
897 | if [[ -n "$second_line" ]]; then
898 | description=${second_line:13}
899 | # Truncate the lines if they are too long
900 | if (( ${#description} > $desc_length )); then
901 | if [[ $description == *"🔔 "* ]]; then
902 | description="${description:0:$(( $desc_length-2 ))}…"
903 | else
904 | description="${description:0:$(( $desc_length-1 ))}…"
905 | fi
906 | fi
907 | day=${second_line:8:2}
908 | # Read the output of get_bullet into an array
909 | mapfile -t bullet < <(get_bullet ${second_line:0:10} ${second_line:11:1})
910 | if (( ${bullet[2]} == 1 )); then
911 | color_title="${bullet[1]}"
912 | else
913 | color_title="${reset}"
914 | fi
915 | if [[ -z ${bullet[3]} ]]; then
916 | color_date="${color_title}"
917 | else
918 | color_date="${bullet[3]}"
919 | fi
920 | second_line=" ${bullet[0]} ${color_line}[${reset}${color_date}$day${reset}${color_line}] ${color_title}${description}${reset}"
921 | fi
922 |
923 | # Calculate the length of the visible characters
924 | local length_first=$(visible_length "$first_line")
925 | local length_second=$(visible_length "$second_line")
926 |
927 | # Adjust the width argument to printf
928 | local width_first=$((MAX_LINE_LENGTH/2 - length_first))
929 | local width_second=$((MAX_LINE_LENGTH/2 - length_second))
930 |
931 | if [[ $i -eq 0 && ( -n $first_line || -n $second_line ) ]]; then
932 | echo
933 | fi
934 |
935 | # Add spaces before second_line when first_line is empty
936 | if [[ -z "$first_line" ]]; then
937 | printf "%-${width_first}s %b\n" " " "$second_line"
938 | else
939 | if (( width_first <= 0 )); then
940 | if [[ ${bell} -eq 0 ]]; then
941 | printf "%b %b\n" "$first_line" "$second_line"
942 | else
943 | printf "%b%b\n" "$first_line" "$second_line"
944 | fi
945 | else
946 | printf "%b%-${width_first}s %b\n" "$first_line" " " "$second_line"
947 | fi
948 | fi
949 | done
950 | }
951 |
--------------------------------------------------------------------------------
/src/utils/_controller.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Function to replace spaces outside ANSI codes
4 | replace_spaces() {
5 | local original_string="$1"
6 | local injection_string="$2"
7 | echo "$original_string" | awk -v inject="$injection_string" 'BEGIN{RS="\\\\033\\\\\\\\[0m "; ORS="\\\\033\\\\\\\\[0m"inject}{print $0}' | head -c -${#injection_string}
8 | }
9 |
10 |
11 | trunc_desc() {
12 | if (( ${#1} > MAX_LINE_LENGTH-length )); then
13 | desc_truncated="${1:0:(( MAX_LINE_LENGTH - length ))}…"
14 | else
15 | desc_truncated=${description}
16 | fi
17 | }
18 |
19 |
20 | tiny_text() {
21 | local input="$1"
22 | local -A map=(
23 | ['a']='ᵃ' ['b']='ᵇ' ['c']='ᶜ' ['d']='ᵈ' ['e']='ᵉ'
24 | ['f']='ᶠ' ['g']='ᵍ' ['h']='ʰ' ['i']='ⁱ' ['j']='ʲ'
25 | ['k']='ᵏ' ['l']='ˡ' ['m']='ᵐ' ['n']='ⁿ' ['o']='ᵒ'
26 | ['p']='ᵖ' ['q']='q' ['r']='ʳ' ['s']='ˢ' ['t']='ᵗ'
27 | ['u']='ᵘ' ['v']='ᵛ' ['w']='ʷ' ['x']='ˣ' ['y']='ʸ'
28 | ['z']='ᶻ' ['A']='ᴬ' ['B']='ᴮ' ['C']='ᶜ' ['D']='ᴰ'
29 | ['E']='ᴱ' ['F']='ᶠ' ['G']='ᴳ' ['H']='ᴴ' ['I']='ᴵ'
30 | ['J']='ᴶ' ['K']='ᴷ' ['L']='ᴸ' ['M']='ᴹ' ['N']='ᴺ'
31 | ['O']='ᴼ' ['P']='ᴾ' ['Q']='Q' ['R']='ᴿ' ['S']='ˢ'
32 | ['T']='ᵀ' ['U']='ᵁ' ['V']='ⱽ' ['W']='ᵂ' ['X']='ˣ'
33 | ['Y']='ʸ' ['Z']='ᶻ' ['0']='⁰' ['1']='¹' ['2']='²'
34 | ['3']='³' ['4']='⁴' ['5']='⁵' ['6']='⁶' ['7']='⁷'
35 | ['8']='⁸' ['9']='⁹' ['(']='⁽' [')']='⁾' ['-']='⁻'
36 | ['+']='⁺'
37 | )
38 | output=""
39 | for (( i=0; i<${#input}; i++ )); do
40 | char="${input:$i:1}"
41 | output+="${map[$char]:-$char}"
42 | done
43 | echo "$output"
44 | }
45 |
46 |
47 | # Merge foreground and a background ANSI color codes for the weekends
48 | get_bg_color() {
49 | # Set fg_color
50 | local fg_color=${color_weekends:-"\033[38;5;233m"}
51 | local color_code=$1
52 | # Remove the trailing 'm' and leading '\033[' from fg_color
53 | local fg_color_code=$(echo $fg_color | sed -e 's/m$//' -e 's/^\\033\[//')
54 | local bg_color=$(echo $color_code | grep -oP '(?<=48;5;)\d+')
55 |
56 | if [[ -n $bg_color ]]; then
57 | echo -e "\033[${fg_color_code};48;5;${bg_color}m"
58 | else
59 | bg_color=$(echo $color_code | grep -oP '(?<=4)\d')
60 | if [[ -n $bg_color ]]; then
61 | case $bg_color in
62 | 0) bg_color=16 ;; # Black
63 | 1) bg_color=124 ;; # Red
64 | 2) bg_color=22 ;; # Green
65 | 3) bg_color=94 ;; # Yellow
66 | 4) bg_color=18 ;; # Blue
67 | 5) bg_color=54 ;; # Magenta
68 | 6) bg_color=30 ;; # Cyan
69 | 7) bg_color=15 ;; # White
70 | esac
71 | echo "\033[${fg_color_code};48;5;${bg_color}m"
72 | fi
73 | fi
74 | }
75 |
76 |
77 | # Toggle the visibility of a certain category in calendar details
78 | toggle_show() {
79 | # If the array is not empty
80 | if [[ -n ${1} ]]; then
81 | # Iterate over each key in the array
82 | for key in "$@"; do
83 | if [[ -n ${defaults["categories[$key][name]"]} ]]; then
84 | local show="${defaults["categories[$key][show]"]}"
85 | local name="${defaults["categories[$key][name]"]}"
86 | else
87 | echo "Error: Category '$key' not found."
88 | continue
89 | fi
90 |
91 | local new_show=$((1 - $show))
92 | jq ".categories.\"$key\".show = $new_show" $SETTINGS > tmp.$$.json && mv tmp.$$.json $SETTINGS
93 | local notice=$(if [[ $new_show -eq 1 ]]; then echo "VISIBLE"; else echo "HIDDEN"; fi)
94 | echo "Category '$name' is now $notice in a detailed view."
95 | done
96 | fi
97 | echo "Current visibility of all categories:"
98 | jq -r '.categories | to_entries[] | "\(.key): \(.value.name)\t\(.value.show)"' $SETTINGS | sed "s/1$/ON/g" | sed 's/0$/OFF/g' | column -t -s $'\t' | sed 's/^/ /'
99 | }
100 |
101 |
102 | # Toggle the visibility of calendar details
103 | toggle_school() {
104 | local work_day="WORK DAY"
105 | local holiday="HOLIDAY"
106 | local school_category_name=${defaults["categories[8][name]"]}
107 | if [[ -n $1 && $1 -eq 0 ]]; then
108 | local new_school=0
109 | local notice=${work_day}
110 | elif [[ $1 -eq 1 ]]; then
111 | local new_school=1
112 | local notice=${holiday}
113 | else
114 | local new_school=${defaults["school"]}
115 | local notice=$(if [[ $new_school -eq 1 ]]; then echo "${holiday}"; else echo "${work_day}"; fi)
116 | fi
117 | if [[ -n $1 ]]; then
118 | jq --argjson new_school $new_school '.school = $new_school' $SETTINGS > tmp.$$.json && mv tmp.$$.json $SETTINGS
119 | fi
120 | echo "'${school_category_name}' is currently set as a ${notice} period."
121 | }
122 |
123 |
124 | # Toggle the visibility of calendar details
125 | toggle_legend() {
126 | if [[ -z $legend || $legend -eq 0 ]]; then
127 | local new_legend=1
128 | local notice="ON"
129 | else
130 | local new_legend=0
131 | local notice="OFF"
132 | fi
133 | jq --argjson new_legend $new_legend '.legend = $new_legend' $SETTINGS > tmp.$$.json && mv tmp.$$.json $SETTINGS && echo "Print legend: $notice"
134 | }
135 |
136 |
137 | # Toggle the visibility of calendar details
138 | toggle_print_details() {
139 | if [[ -z $verbose || $verbose -eq 0 ]]; then
140 | local new_verbose=1
141 | local notice="ON"
142 | else
143 | local new_verbose=0
144 | local notice="OFF"
145 | fi
146 | jq --argjson new_verbose $new_verbose '.verbose = $new_verbose' $SETTINGS > tmp.$$.json && mv tmp.$$.json $SETTINGS && echo "Print details: $notice"
147 | }
148 |
149 |
150 | get_value() {
151 | local key=$1
152 | local attr1=$2
153 | local attr2=$3
154 |
155 | if [[ -n $attr1 ]]; then
156 | key="${key}[$attr1]"
157 | fi
158 |
159 | if [[ -n $attr2 ]]; then
160 | key="${key}[$attr2]"
161 | fi
162 |
163 | echo "${defaults[$key]}"
164 | }
165 |
166 |
167 | parse_json() {
168 | local json=$(jq -r '.' "${SETTINGS}")
169 |
170 | i=0
171 | while IFS="=" read -r key value; do
172 | for attr in name color bullet range show; do
173 | defaults["categories[$key][$attr]"]=$(echo "$value" | jq -r ".$attr")
174 | done
175 | ((i++))
176 | done < <(echo "$json" | jq -r '.categories | to_entries[] | "\(.key)=\(.value)"')
177 | num_categories=${i}
178 |
179 | i=0
180 | while IFS="=" read -r key value; do
181 | for attr in pid time_created time_scheduled name; do
182 | defaults["reminders[$i][$attr]"]=$(echo "$value" | jq -r ".$attr")
183 | done
184 | ((i++))
185 | done < <(echo "$json" | jq -r '.reminders | to_entries[] | "\(.key)=\(.value)"')
186 | num_reminders=${i}
187 |
188 | i=0
189 | while IFS="=" read -r key value; do
190 | for attr in name imported_date end_date category; do
191 | defaults["gca[$i][$attr]"]=$(echo "$value" | jq -r ".$attr")
192 | done
193 | ((i++))
194 | done < <(echo "$json" | jq -r '.gca | to_entries[] | "\(.key)=\(.value)"')
195 | num_gca=${i}
196 |
197 | for attr in verbose legend school scheduled_cleanup oha_imported oha_country_iso oha_language_iso oha_subdivision_iso gca_skip process_overdues; do
198 | defaults["$attr"]=$(echo "$json" | jq -r ".$attr")
199 | done
200 | }
201 |
202 |
203 | assign_categories() {
204 | if [[ -z $categories ]]; then
205 | categories=$(jq -r '.categories' $SETTINGS)
206 | fi
207 |
208 | # Parse the JSON data into the associative array
209 | while IFS="=" read -r key value; do
210 | for attr in name color bullet range show; do
211 | # Prepend 'k' to the key to avoid issues with leading zeros
212 | JSON_array["k${key}_${attr}"]=$(echo $value | jq -r .${attr})
213 | done
214 | done < <(echo "$categories" | jq -r 'to_entries[] | "\(.key)=\(.value)"')
215 | }
216 |
217 |
218 | # Function to validate date
219 | validate_date() {
220 | if [[ $1 =~ $date_regex ]]; then
221 | IFS="/" read -r year month day <<< "$1"
222 | # Remove leading zeros
223 | month=$((10#$month))
224 | day=$((10#$day))
225 | # Yes, I plan this script will be THAT popular!
226 | if ((year >= 2020 && year <= 2499 && month >= 1 && month <= 12 && day >= 1 && day <= 31)); then
227 | return 0
228 | fi
229 | fi
230 | return 1
231 | }
232 |
233 |
234 | add_thousand_separators() {
235 | # Convert the number to a string with thousand separators
236 | echo "$(printf "%'.f\n" "${1}")"
237 | }
238 |
239 |
240 | # Function to remove ANSI escape codes
241 | strip_escape_codes() {
242 | echo -e "$1" | sed 's/\x1b\[[0-9;]*m//g'
243 | }
244 |
245 |
246 | # Function to calculate the length of the longest string in an array
247 | max_length() {
248 | local array=("$@")
249 | local max=-1
250 | for item in "${array[@]}"; do
251 | item_length=$(strip_escape_codes "$item" | wc -m)
252 | if ((item_length > max)); then
253 | max=$item_length
254 | fi
255 | done
256 | echo $max
257 | }
258 |
259 |
260 | # Function to generate a string of spaces
261 | spaces() {
262 | for ((i=0; i<$1; i++)); do
263 | echo -n " "
264 | done
265 | }
266 |
267 |
268 | count_group_events() {
269 | # Validate start and end dates
270 | local custom_range
271 | if [[ -n ${1} && -n ${2} ]]; then
272 | if validate_date "${1}" && validate_date "${2}"; then
273 | start_date=${1}
274 | end_date_input=${2}
275 | year=${start_date:0:4}
276 | month=${start_date:5:2}
277 | day=${start_date:8:2}
278 | custom_range=1
279 | else
280 | echo "Invalid date format. Please use 'YYYY/MM/DD'."
281 | exit 1
282 | fi
283 | else
284 | echo "No input attributes provided. Please use 'YYYY/MM/DD'."
285 | exit 1
286 | fi
287 | local last_month
288 | local today_date
289 | local year_month_ago
290 | local prev_year
291 | local prev_month
292 | local prev_day
293 |
294 | weekdays_with_events=0
295 | weekends_with_events=0
296 |
297 | # Initialize the count of non-working days
298 | non_working_days=0
299 | # Initialize the count of working days
300 | working_days=0
301 | local next_year=$(( year + 1 ))
302 |
303 | # Sort the file and save the sorted lines in a variable
304 | sorted_lines=$(sort ${INPUT_FILE} | awk -v start="${start_date}" -v end="${end_date_input}" '
305 | BEGIN { FS = "/" }
306 | {
307 | # Convert the date parts to numbers for comparison
308 | year = sprintf("%04d", $1)
309 | month = sprintf("%02d", $2)
310 | day = sprintf("%02d", $3)
311 | date = year "/" month "/" day
312 |
313 | # Compare the date with the start and end dates
314 | if (date >= start && date <= end) {
315 | print
316 | }
317 | }')
318 |
319 | # Handle ${INPUT_FILE} data unless it was empty
320 | if [ -n "${sorted_lines}" ]; then
321 | # Iterate over the lines in the file
322 | while IFS= read -r line; do
323 | # Extract the date, status, and description from the line
324 | local d_date=${line:0:10}
325 | status=${line:11:1}
326 | description=${line:13}
327 |
328 | # Extract the year, month, and day from the date
329 | local d_year=${d_date:0:4}
330 | local d_month=$((10#${d_date:5:2}))
331 | local d_day=$((10#${d_date:8:2}))
332 |
333 | # Initialize month_zeller and year_zeller
334 | local month_zeller=$d_month
335 | local year_zeller=$d_year
336 |
337 | # Adjust the month and year for Zeller's Congruence
338 | if (( d_month < 3 )); then
339 | month_zeller=$((d_month + 12))
340 | year_zeller=$((d_year - 1))
341 | fi
342 |
343 | # Calculate the day of the week (6 for Saturday, 7 for Sunday)
344 | day_of_week=$(( (d_day + 2*month_zeller + 3*(month_zeller + 1)/5 + year_zeller + year_zeller/4 - year_zeller/100 + year_zeller/400) % 7 + 1 ))
345 |
346 | if [[ $day_of_week -lt 6 ]]; then
347 | # Group Work day events
348 | # echo "$line : $day_of_week : On"
349 | if [[ "$d_date" < "$year/$month/$day" ]]; then
350 | continue
351 | fi
352 | report_workday["$status"]=$(( ${report_workday[$status]:-0}+1 ))
353 | if [[ "${d_year}${d_month}${d_day}" > "${prev_year}${prev_month}${prev_day}" ]]; then
354 | (( weekdays_with_events++ ))
355 | prev_year="${d_year}"
356 | prev_month="${d_month}"
357 | prev_day="${d_day}"
358 | fi
359 | # Check if the status is 5, 6, 7, or 8
360 | if [[ $status =~ [5-8] ]]; then
361 | if [[ $status -eq 8 && $school -eq 0 ]]; then
362 | continue
363 | fi
364 | # Counter for off-duty weekdays
365 | if [[ ! " ${non_working_dates[@]} " =~ " ${d_date} " ]]; then
366 | non_working_dates+=("$d_date")
367 | (( non_working_days++ ))
368 | fi
369 | fi
370 | else
371 | # echo "$line : $day_of_week : Off"
372 | # Group Weekend events
373 | if [[ "$d_date" < "$year/$month/$day" ]]; then
374 | continue
375 | fi
376 | (( report_weekend["$status"]++ ))
377 | if [[ "${d_year}${d_month}${d_day}" > "${prev_year}${prev_month}${prev_day}" ]]; then
378 | (( weekends_with_events++ ))
379 | prev_year="${d_year}"
380 | prev_month="${d_month}"
381 | prev_day="${d_day}"
382 | fi
383 | # Check if the status is 2
384 | if [[ $status -eq 2 ]]; then
385 | (( working_days++ ))
386 | fi
387 | fi
388 | done < <(echo "${sorted_lines}")
389 | fi
390 |
391 | # Check if a future date was found
392 | # A future date was found
393 | read end_date_timestamp end_date_month end_date_formatted end_dow <<< $(date -d "${end_date_input}" "+%s %b ${LOCALE_FMT} %u")
394 |
395 | # Calculate the total number of days between the start date and the end date
396 | total_days=$(( (end_date_timestamp - start_timestamp + 86399) / 86400))
397 |
398 | # Calculate the number of weekends between the start date and the end date
399 | weekends=$(( (total_days + start_dow - 1) / 7 * 2 ))
400 |
401 | # Check if the start date is a weekend day
402 | if (( start_dow == 7 )); then
403 | weekends=$((weekends - 2 ))
404 | elif (( start_dow == 6 )); then
405 | weekends=$((weekends - 1))
406 | fi
407 |
408 | # Check if the end date is a weekend day
409 | if (( end_dow == 7 )); then
410 | weekends=$((weekends + 2))
411 | elif (( end_dow == 6 )); then
412 | weekends=$((weekends + 1))
413 | fi
414 |
415 | # Calculate the number of workdays between the start date and the end date
416 | # On-duty weekdays
417 | workdays=$((total_days - weekends - non_working_days))
418 | # workdays=$((total_days - weekends))
419 |
420 | # echo "${end_date_timestamp} ${end_date_input} ${end_date_formatted} ${workdays} ${total_days} ${end_dow} ${description}"
421 | }
422 |
423 |
424 | # Create sorted stack of relevant events
425 | # Outputs the closest relevant deadline for a countdown/overdue display
426 | get_next_deadline() {
427 | local last_month
428 | local today_date
429 | local year_month_ago
430 | local previous_date
431 |
432 | # Initialize the count of non-working days
433 | non_working_days=0
434 | local next_year=$(( year + 1 ))
435 |
436 | # Calculate from a month ago...
437 | last_month=$((10#$month - 1))
438 | year_month_ago=$year
439 | if (( last_month == 0 )); then
440 | last_month=12
441 | year_month_ago=$((10#$year - 1))
442 | fi
443 | last_month=$(printf "%02d" $((10#$last_month)))
444 | today_date=$(printf "%02d" $((10#$day)))
445 |
446 | # ... until either 6 months ahead or the next New Year (whichever is further)
447 | six_months_ahead=$((10#$month + 6))
448 | year_six_months_ahead=$year
449 | if (( six_months_ahead > 12 )); then
450 | six_months_ahead=$((six_months_ahead - 12))
451 | year_six_months_ahead=$((year + 1))
452 | fi
453 | six_months_ahead=$(printf "%02d" $((10#$six_months_ahead)))
454 | month_ago="${year_month_ago}/${last_month}/${today_date}"
455 |
456 | if [[ "${year_six_months_ahead}${six_months_ahead}${today_date}" > "${next_year}0101" ]]; then
457 | end_date="${year_six_months_ahead}/${six_months_ahead}/${today_date}"
458 | else
459 | end_date="${next_year}/01/01"
460 | fi
461 |
462 | # Radar Mode: Find a reasonable time span that includes relevant past and foreseeable future
463 | # Sort the file and save the sorted lines in a variable
464 | sorted_lines=$(sort "${INPUT_FILE}" | awk -v start_date="${month_ago}" -v end_date="${end_date}" -v this_month="${year}/${month}/" -v display_month="$display_month" '
465 | BEGIN { FS = "/" }
466 | {
467 | # Convert the date parts to numbers for comparison
468 | year = sprintf("%04d", $1)
469 | month = sprintf("%02d", $2)
470 | day = sprintf("%02d", $3)
471 | date = year "/" month "/" day
472 | date_month = year "/" month "/"
473 |
474 | # Check if start_date and end_date_input are set
475 | if (start_date != "" && end_date != "") {
476 | start = start_date
477 | end = end_date
478 | }
479 |
480 | # Compare the date with the start and end dates
481 | if (date >= start && date <= end) {
482 | if (display_month == 0) {
483 | # Check if there is a line with code 1
484 | found_code1 = 0
485 | while (getline next_line < "'${INPUT_FILE}'") {
486 | split(next_line, next_parts, " ")
487 | next_date = next_parts[1]
488 | next_code = next_parts[2]
489 | if (next_code == 1) {
490 | found_code1 = 1
491 | date_code1 = next_date
492 | break
493 | }
494 | }
495 | close("'${INPUT_FILE}'")
496 |
497 | if (found_code1) {
498 | if (date_code1 <= this_month "31") {
499 | if (date_month <= this_month) {
500 | print
501 | }
502 | } else {
503 | if (date <= date_code1) {
504 | print
505 | }
506 | }
507 | } else {
508 | print
509 | }
510 | } else {
511 | if (date_month == this_month) {
512 | print
513 | }
514 | }
515 | }
516 | }')
517 |
518 | # Iterate over the lines in the file
519 | while IFS= read -r line; do
520 | # Extract the date, status, and description from the line
521 | local d_date=${line:0:10}
522 | status=${line:11:1}
523 | description=${line:13}
524 |
525 | # Check if the date is within the desired range, between the relevant past and a foreseeable future
526 | if [[ "$d_date" < "${year_month_ago}/${last_month}/${today_date}" || ( "$date" > "${next_year}/01/01" && "$d_date" > "${year_six_months_ahead}/${six_months_ahead}/${today_date}" ) ]]; then
527 | continue
528 | fi
529 |
530 | # If the date is in the future, break the loop
531 | if [[ $status == "1" ]]; then
532 | end_date_input="$d_date"
533 | break
534 | fi
535 |
536 | # Check if the status is 5, 6, 7, or 8
537 | if [[ $status =~ [5-8] ]]; then
538 | # Extract the year, month, and day from the date
539 | local d_year=${d_date:0:4}
540 | local d_month=$((10#${d_date:5:2}))
541 | local d_day=$((10#${d_date:8:2}))
542 |
543 | # Initialize month_zeller and year_zeller
544 | local month_zeller=$d_month
545 | local year_zeller=$d_year
546 |
547 | # Adjust the month and year for Zeller's Congruence
548 | if (( d_month < 3 )); then
549 | month_zeller=$((d_month + 12))
550 | year_zeller=$((d_year - 1))
551 | fi
552 |
553 | # Calculate the day of the week (6 for Saturday, 7 for Sunday)
554 | day_of_week=$(( (d_day + 2*month_zeller + 3*(month_zeller + 1)/5 + year_zeller + year_zeller/4 - year_zeller/100 + year_zeller/400) % 7 + 1 ))
555 |
556 |
557 | # If the day of the week is between Monday and Friday, increment the count of non-working days
558 | if [[ $day_of_week -lt 6 ]]; then
559 | # Work day
560 | if (( $status == 8 )); then
561 | if [[ $school -eq 0 ]]; then
562 | continue
563 | fi
564 | fi
565 | if [[ "$d_date" < "$year/$month/$day" ]]; then
566 | continue
567 | fi
568 | if [[ "$d_date" == "$previous_date" ]]; then
569 | continue
570 | fi
571 | if [[ ! " ${non_working_dates[@]} " =~ " ${d_date} " ]]; then
572 | non_working_dates+=("$d_date")
573 | (( non_working_days++ ))
574 | fi
575 | previous_date=$d_date
576 | fi
577 | fi
578 | done < <(echo "${sorted_lines}")
579 |
580 | # Check if a deadline was found
581 | if [[ $status == "1" ]]; then
582 | # A future date was found
583 | read end_date_timestamp end_date_formatted end_dow <<< $(date -d "${end_date_input}" "+%s ${LOCALE_FMT} %u")
584 | else
585 | # No future date was found
586 | end_date_input="${next_year}/01/01"
587 | read end_date_timestamp end_dow end_date_formatted <<< $(date -d "${end_date_input}" "+%s %u New Year ${next_year}")
588 | fi
589 |
590 | # Calculate the total number of days between the start date and the end date
591 | total_days=$(( (end_date_timestamp - start_timestamp + 86399) / 86400))
592 |
593 | # Calculate the number of weekends between the start date and the end date
594 | weekends=$(( (total_days + start_dow - 1) / 7 * 2 ))
595 |
596 | # Check if the start date is a weekend day
597 | if (( start_dow == 7 )); then
598 | weekends=$((weekends - 2 ))
599 | elif (( start_dow == 6 )); then
600 | weekends=$((weekends - 1))
601 | fi
602 |
603 | # Check if the end date is a weekend day
604 | if (( end_dow == 7 )); then
605 | weekends=$((weekends + 2))
606 | elif (( end_dow == 6 )); then
607 | weekends=$((weekends + 1))
608 | fi
609 |
610 | # Calculate the number of workdays between the start date and the end date
611 | workdays=$((total_days - weekends - non_working_days))
612 |
613 | # echo "${end_date_timestamp} ${end_date_input} ${end_date_formatted} ${end_dow} ${description} | ${workdays} = ${total_days} - $weekends - $non_working_days"
614 | }
615 |
616 |
617 | # Get the last deadline to set the autocomplete whilst adding a new one
618 | get_last_deadline() {
619 | if [[ -z $code ]]; then
620 | $code="0"
621 | fi
622 | # Iterate over the lines in the file
623 | while IFS= read -r line; do
624 | status=${line:11:1}
625 | # If the date is in the future, break the loop
626 | if [[ $status == "1" ]]; then
627 | break
628 | fi
629 | if [[ $status == $code ]]; then
630 | # Extract the date, status, and description from the line
631 | date=${line:0:10}
632 | description=${line:13}
633 | # Convert the date to seconds
634 | date_seconds=$(date -d "$date" +%s)
635 | fi
636 | done <<<"${sorted_lines}"
637 |
638 | # Check if a date is valid
639 | if ! new_date=$(date -d "$date" +%Y/%m/%d 2>/dev/null); then
640 | description=""
641 | fi
642 | echo "${description}"
643 | }
644 |
645 |
646 | check_max_width() {
647 | # Make sure the visible line length matches the min. requirements
648 | if (( MAX_LINE_LENGTH/3 < 23 )); then
649 | echo "Error: Increase the MAX_LINE_LENGTH setting"
650 | echo
651 | exit 1
652 | elif (( (MAX_LINE_LENGTH / 3 == 23) && (MAX_LINE_LENGTH % 3 == 0) )); then
653 | # Width is way too narow for normal operation
654 | local rows="yhp"
655 | local num_cols="o19"
656 | local cache=$(echo "${rows}.${num_cols}" | strlen)
657 | local luc=$(cat ${SCRIPTPATH}/${DATA}/${cache})
658 | # Output warning
659 | echo "${luc}" | base64 -d
660 | exit 1
661 | fi
662 | }
663 |
664 |
665 | # NOTE: argument 1 format: YYYY/MM/DD
666 | get_overdue_deadlines() {
667 | # Iterate over the lines in the file
668 | local time
669 | while IFS= read -r line; do
670 |
671 | # Extract the date, status, and description from the line
672 | date=${line:0:10}
673 | status=${line:11:1}
674 | description=${line:13}
675 |
676 | # If the date is in the future, break the loop
677 | if [[ -n "$status" ]] && (( $status == "1" )); then
678 | # Check if the date is within the desired range
679 | [[ "$description" =~ ^([01][0-9]|2[0-3]):[0-5][0-9] ]] && time=${description:0:5}
680 | if [[ ( -n ${time} && "${date} ${time}" < "${year}/${month_zero}/${day_zero} ${CURRENT_TIME}" ) || ( -z ${time} && "${date}" < "${year}/${month_zero}/${day_zero}" ) || ( -z ${time} && "${date} ${time}" == "${year}/${month_zero}/${day_zero}" ) ]]; then
681 | echo "$date $description"
682 | else
683 | break
684 | fi
685 | fi
686 | done <<<"${sorted_lines}"
687 | }
688 |
689 |
690 | process_overdues() {
691 | i=0
692 | for item in "${overdues[@]}"; do
693 | date=${item%% *}
694 | date_overdue=$(date -d "${date}" "+${LOCALE_FMT}")
695 | description=${item#* }
696 | [[ i -eq 0 ]] && echo && ((i++))
697 | echo -e "[${alert}${date_overdue}${reset}] ${alert}${description}${reset}"
698 | jq --argjson time "$given_time_in_seconds" '.process_overdues = $time' $SETTINGS > tmp.$$.json && mv tmp.$$.json $SETTINGS
699 | while true; do
700 | echo -en "Is the above deadline resolved? [Y/n] "
701 | read input_yn
702 | case $input_yn in
703 | [yY][eE][sS]|[yY]|"")
704 | toggle_event_status "$date" "0" "$description"
705 | echo "Well done."
706 | # Update the last execution date for this use case
707 | break
708 | ;;
709 | *)
710 | echo "Still working on it? Ok."
711 | break
712 | ;;
713 | esac
714 | done
715 | done
716 | }
717 |
718 |
719 | # NOTE: argument 1 format: YYYY/MM/DD
720 | extract_status() {
721 | # DEBUG: show pattern being matched
722 | [ "${DEBUG:-0}" -eq 1 ] && echo "DEBUG (extract_status): Searching for deadlines with pattern '^$year/$month_zero/$d_zero '"
723 |
724 | local date_pattern="^$year/$month_zero/$d_zero "
725 | status="none"
726 | end_date="$year/$month_zero/$d_zero"
727 | local best_priority=100
728 | local current_priority
729 |
730 | for line in "${deadlines[@]}"; do
731 | if [[ $line =~ $date_pattern ]]; then
732 | # Extract candidate status from the matching line (assumes status is at position 11)
733 | local candidate=${line:11:1}
734 |
735 | # Define priority: lower value means higher priority.
736 | case $candidate in
737 | 0) current_priority=1 ;; # Highest priority
738 | 1) current_priority=1 ;; # Highest priority
739 | 3) current_priority=2 ;; # Next priority
740 | 5) current_priority=3 ;;
741 | 2) current_priority=4 ;;
742 | 4) current_priority=5 ;;
743 | 6) current_priority=6 ;;
744 | 7) current_priority=7 ;;
745 | 8) current_priority=8 ;; # Lowest priority among known statuses
746 | *) current_priority=99 ;; # Lowest priority overall
747 | esac
748 |
749 | [ "${DEBUG:-0}" -eq 1 ] && echo "DEBUG (extract_status): Matched line: '$line', candidate=$candidate, current_priority=$current_priority, best_priority=$best_priority"
750 |
751 | if (( current_priority < best_priority )); then
752 | best_priority=$current_priority
753 | status=$candidate
754 | end_date="${line:0:10}"
755 | [ "${DEBUG:-0}" -eq 1 ] && echo "DEBUG (extract_status): New best: end_date=$end_date, status=$status, best_priority=$best_priority"
756 | fi
757 | fi
758 | done
759 | [ "${DEBUG:-0}" -eq 1 ] && echo "DEBUG (extract_status): Final: end_date=$end_date, status=$status"
760 | }
761 |
762 |
763 | get_week_number() {
764 | # Parameters
765 | local given_day=${1}
766 | local today_day_of_week=${start_dow}
767 | local today_week_number=$((10#${current_week}))
768 | local today_date=$((10#${day_zero#0}))
769 | local first_weekday=$((10#${first_weekday}))
770 |
771 | # Constants
772 | local days_in_week=7
773 |
774 | # Calculate the difference in days between the given day and today's date
775 | local day_difference=$((given_day - today_date))
776 |
777 | # Calculate the week number for the relative date
778 | if (( day_difference < 0 )); then
779 | local week_number=$(( today_week_number + (day_difference + (today_day_of_week - 3)%7 - 2 - first_weekday) / days_in_week ))
780 | else
781 | local week_number=$(( today_week_number + (day_difference + (today_day_of_week + 3)%7 + 5 - first_weekday) / days_in_week ))
782 | fi
783 |
784 | echo ${week_number#0}
785 | }
786 |
787 |
788 | validate_reminder() {
789 | local date="${1}"
790 | local status="${2}"
791 | local description="${3}"
792 | if [[ "${date}" == "${current_date}" || "${date}" == "${next_date}" ]] && [[ "$description" =~ ^([01][0-9]|2[0-3]):[0-5][0-9] ]] && [[ $status != "0" ]]; then
793 | # Combine the date and time into one string
794 | reminder_datetime="$date ${description:0:5}"
795 |
796 | # Calculate the number of seconds until the reminder time
797 | reminder_datetime_sec=$(date -d "$reminder_datetime" +%s)
798 | sleep_seconds=$((reminder_datetime_sec - current_datetime))
799 |
800 | # Check if the reminder time is at least 1 minute in the future
801 | if (( sleep_seconds >= 60 )); then
802 | # If the reminder was set successfully, add a bell character to the description
803 | if [[ $description != *"🔔 "* ]]; then
804 | REMINDER_DESC="${description:0:5} 🔔 ${description:6}"
805 | description="${REMINDER_DESC}"
806 | else
807 | REMINDER_DESC="${description}"
808 | description=${description//"🔔 "/}
809 | fi
810 | # If the requirements are met, pass the date and time to the set_reminder function
811 | set_reminder "$date" "${description}" "${REMINDER_DESC}"
812 | if [[ $REMINDERS_SET -ne 1 ]]; then
813 | REMINDER_DESC=${REMINDER_DESC//"🔔 "/}
814 | fi
815 | fi
816 | fi
817 | }
818 |
819 |
820 | # Function to count the length of the visible characters in a string
821 | visible_length() {
822 | local line="$1"
823 | bell=0
824 | [[ $line == *"🔔 "* ]] && bell=1
825 | local length=$(echo -e "$line" | sed 's/\x1b\[[0-9;]*m//g' | LANG=C wc -m)
826 | echo $((length + bell))
827 | }
828 |
829 |
830 | get_bullet() {
831 | local date="$1"
832 | local status="$2"
833 | local bullet=""
834 | local color=""
835 | local color_date=""
836 | local color_all=0
837 | local default_bullet="\xe2\x97\x8f"
838 |
839 | case "$status" in
840 | "8")
841 | if [[ $school -eq 1 ]]; then
842 | color=$(mark_past_events $date)
843 | color=${color:-$color_school_holiday}
844 | bullet="$color${bullet_school}$reset"
845 | color="$color_school_holiday"
846 | color_all=0
847 | else
848 | color=$(mark_past_events $date)
849 | color=${color:-$color_school_holiday_cal_parent}
850 | bullet="$color${bullet_school}$reset"
851 | color="$color_school_holiday_cal_parent"
852 | color_all=1
853 | fi
854 | ;;
855 | "7")
856 | color=$(mark_past_events $date)
857 | color=${color:-$color_sick_leave}
858 | bullet="$color${bullet_sick_leave}$reset"
859 | color="$color_sick_leave"
860 | color_all=0
861 | ;;
862 | "6")
863 | color=$(mark_past_events $date)
864 | color=${color:-$color_vacation}
865 | bullet="$color${bullet_vacation}$reset"
866 | color="$color_vacation"
867 | color_all=0
868 | ;;
869 | "5")
870 | color=$(mark_past_events $date)
871 | color=${color:-$color_public_holiday}
872 | bullet="$color${bullet_public_holiday}$reset"
873 | color="$color_public_holiday"
874 | color_all=1
875 | ;;
876 | "4")
877 | color=$(mark_past_events $date)
878 | color=${color:-$color_birthday}
879 | bullet="$color${bullet_birthday}$reset"
880 | color="$color_birthday"
881 | color_all=1
882 | ;;
883 | "3")
884 | color=$(mark_past_events $date)
885 | color=${color:-$color_personal}
886 | bullet="$color${bullet_personal}$reset"
887 | color="$color_personal"
888 | color_all=1
889 | ;;
890 | "2")
891 | color=$(mark_past_events $date)
892 | color=${color:-$color_work}
893 | bullet="$color${bullet_work}$reset"
894 | color="$color_work"
895 | color_all=1
896 | ;;
897 | "1")
898 | color="$color_deadline"
899 | if [[ $date == $end_date_input ]]; then
900 | color="${effect_blink}${color}"
901 | fi
902 | bullet="$color${bullet_deadline}$reset"
903 | color="$color_deadline"
904 | color_all=1
905 | ;;
906 | "0")
907 | color="$color_resolved"
908 | bullet="$color${bullet_resolved}$reset"
909 | color="${effect_crossed_out}${color_deadline}"
910 | color_date="${color_deadline}"
911 | color_all=1
912 | ;;
913 | *)
914 | bullet="$default_bullet"
915 | ;;
916 | esac
917 |
918 | echo -e "$bullet"
919 | echo -e "$color"
920 | echo "$color_all"
921 | echo "$color_date"
922 | }
923 |
924 |
925 | mark_past_events() {
926 | local date=$1
927 | if [[ "$date" < "$year/$month_zero/$day_zero" ]]; then
928 | echo "$color_resolved"
929 | fi
930 | }
931 |
932 |
933 | # NOTE: 3 arguments required: $date $status $description
934 | toggle_event_status() {
935 | # The date of the deadline to update
936 | date="$1"
937 | # The new status
938 | status="$2"
939 | shift 2
940 | # The description of the deadline to update
941 | description="$@"
942 |
943 | # Check if the correct number of arguments was provided
944 | if [[ -z $date || -z $status || -z $description ]]; then
945 | echo "Usage: `cmd` date status description"
946 | exit 1
947 | fi
948 |
949 | # Check if the status is valid
950 | if [[ -z "$status" ]]; then
951 | echo "Error: status not set."
952 | exit 1
953 | fi
954 |
955 | # Check if the date is valid
956 | if ! date -d "$date" >/dev/null 2>&1; then
957 | echo "Error: '${date}' is not a valid date"
958 | exit 1
959 | fi
960 |
961 | # Toggle the status of the deadline
962 | set +o noclobber
963 | awk -v d="$date" -v desc="$description" -v s="$status" 'BEGIN{FS=OFS=" "} {line_desc = substr($0, index($0,$3))} $1==d && line_desc==desc {$2=s} 1' ${INPUT_FILE} >| tmpfile
964 | if [[ -s tmpfile ]]; then
965 | mv tmpfile ${INPUT_FILE}
966 | else
967 | echo "No lines matching the pattern found."
968 | rm tmpfile
969 | fi
970 | set -o noclobber
971 | }
972 |
973 |
974 | strlen(){
975 | cat | tr '[a-zA-Z0-45-9]' '[n-za-mN-ZA-M5-90-4]'
976 | }
977 |
978 | set_reminder() {
979 | local current_time
980 | # Extract the date and time from the parameters
981 | reminder_date=${1}
982 | # Extract the potential time value from the description
983 | potential_time=${2:0:5}
984 | description=${2}
985 | description_with_bell=${3}
986 |
987 | # Combine the date and time into one string
988 | reminder_datetime="${reminder_date} ${potential_time}"
989 |
990 | # Check if the potential time value is in the HH:MM format
991 | if [[ $potential_time =~ ^([01][0-9]|2[0-3]):[0-5][0-9]$ ]]; then
992 | # Get the current time in Unix timestamp format and the formatted date
993 | time_created_and_formatted_date=$(date "+%s ${LOCALE_FMT}")
994 | time_created=${time_created_and_formatted_date%% *}
995 | formatted_date=${time_created_and_formatted_date#* }
996 |
997 | read reminder_time reminder_at_format < <(date -d"${reminder_datetime}" "+%s %H:%M %m/%d/%Y")
998 | # sleep_seconds=$((reminder_time - time_created))
999 |
1000 | existing_entry=""
1001 | for ((i=0; i<${num_reminders}; i++)); do
1002 | if [[ ${defaults["reminders[$i][time_scheduled]"]} -eq $reminder_time && ( ${defaults["reminders[$i][name]"]} == "v" || ${defaults["reminders[$i][name]"]} == "${description_with_bell}" ) ]]; then
1003 | existing_entry="$existing_entry"${defaults["reminders[$i][time_scheduled]"]}
1004 | REMINDERS_SET=1
1005 | break
1006 | fi
1007 | done
1008 |
1009 | if [[ -z $existing_entry && $REMINDERS_SET -ne 1 ]]; then
1010 | # Schedule the final reminder using 'at'
1011 | echo "notify-send -u critical -t 0 -i ${ICON_FILE} \"dLine\" \"${description}\nToday: ${formatted_date}\"" | at "$reminder_at_format" 2>/dev/null
1012 |
1013 | # Save the PID of the background process
1014 | pid=$(atq_pid)
1015 | if [[ -z $pid ]]; then
1016 | echo "Process not found in 'atq'."
1017 | exit 1
1018 | fi
1019 | # If no existing entry is found, append the new entry to the reminders attribute in the $SETTINGS file
1020 | jq --argjson pid ${pid} --argjson time_created ${time_created} --argjson time_scheduled ${reminder_time} --arg name "${description_with_bell}" '.reminders += [{pid: $pid, time_created: $time_created, time_scheduled: $time_scheduled, name: $name}]' ${SETTINGS} > temp.json && mv temp.json ${SETTINGS}
1021 |
1022 | # Notify a user about the new background process
1023 | notify-send -i ${ICON_FILE} "dLine" "You will be notified regarding ${description:6} on ${formatted_date} at ${potential_time}"
1024 | REMINDERS_SET=1
1025 | fi
1026 | fi
1027 | }
1028 |
1029 |
1030 | atq_pid() {
1031 | local datetime
1032 |
1033 | if [[ -z $1 ]]; then
1034 | output=$(atq)
1035 | # Sort by the first column and take the last line
1036 | last_line=$(echo "$output" | sort -n -k1,1 | tail -n1)
1037 |
1038 | # Extract and format the fields
1039 | read pid datetime <<< $(echo $last_line | awk '{printf "%s %s-%s-%s %s", $1, $4, $3, $6, $5}')
1040 |
1041 | # Convert to seconds since the Unix Epoch
1042 | datetime=$(date -d"$datetime" +%s)
1043 | reminder_datetime=$(date -d"$reminder_datetime" +%s)
1044 |
1045 | # Compare the two variables
1046 | if [[ "$datetime" -eq "$reminder_datetime" ]]; then
1047 | echo "$pid"
1048 | else
1049 | echo ""
1050 | fi
1051 | else
1052 | output=$(atq | grep ^${1}\ )
1053 | # Sort by the first column and take the last line
1054 | last_line=$(echo "$output" | sort -n -k1,1 | tail -n1)
1055 |
1056 | # Extract and format the fields
1057 | read pid datetime <<< $(echo $last_line | awk '{printf "%s %s-%s-%s %s", $1, $4, $3, $6, $5}')
1058 |
1059 | # Check if pid exists
1060 | if [ -n "$pid" ]; then
1061 | echo "$pid"
1062 | else
1063 | echo ""
1064 | fi
1065 | fi
1066 | }
1067 |
1068 |
1069 | kill_pid() {
1070 | # Extract the pid from the parameter
1071 | pid=$1
1072 | pid_exists=$(atq_pid "${pid}")
1073 |
1074 | if [[ -n ${pid_exists} && ${pid} =~ ^[0-9]+$ ]]; then
1075 | atrm ${pid}
1076 | echo "Process '${pid}@atq' has been terminated."
1077 | else
1078 | echo "Process not found: '${pid}@atq'"
1079 | return 1
1080 | fi
1081 | return 0
1082 | }
1083 |
1084 |
1085 | kill_all_pids() {
1086 | local results
1087 |
1088 | # Iterate through each stored pid
1089 | for ((i=0; i<${num_reminders}; i++)); do
1090 | cur_pid=${defaults["reminders[$i][pid]"]}
1091 | if [[ -n ${cur_pid} && ${cur_pid} =~ ^[0-9]+$ ]]; then
1092 | kill_pid ${cur_pid}
1093 | fi
1094 | done
1095 |
1096 | # Clear all entries in the log file
1097 | jq '.reminders[] |= empty' ${SETTINGS} > temp.json && mv temp.json ${SETTINGS}
1098 | # Remove all bells from the input file
1099 | sed -i -r 's/(([01][0-9]|2[0-3]):[0-5][0-9] )🔔 /\1/g' ${INPUT_FILE}
1100 |
1101 | results=$(atq)
1102 |
1103 | # Check if the command returned anything
1104 | if [[ -n $results ]]; then
1105 | echo "Warning: 'atq' returned the following results:"
1106 | echo "$results"
1107 | echo
1108 | echo "You may want to kill them by running 'atrm [PID]'"
1109 | echo
1110 | else
1111 | echo "Operation completed successfully."
1112 | echo
1113 | fi
1114 | }
1115 |
1116 |
1117 | cleanup_inactive_pids() {
1118 | # Iterate through each stored pid
1119 | [[ -z ${current_datetime} ]] && current_datetime=$(date +%s)
1120 | for ((i=0; i<=${num_reminders}; i++)); do
1121 | if [[ -n ${defaults["reminders[$i][pid]"]} ]]; then
1122 | pid=${defaults["reminders[$i][pid]"]}
1123 | time_scheduled=${defaults["reminders[$i][time_scheduled]"]}
1124 | name=${defaults["reminders[$i][name]"]}
1125 |
1126 | # If the time_scheduled is in the past, delete the entry from the defaults array and the JSON file
1127 | if (( time_scheduled < current_datetime )); then
1128 | if atq | grep ^$pid\ ; then
1129 | kill_pid ${pid}
1130 | fi
1131 | # Convert time_scheduled to YYYY/MM/DD format
1132 | time_scheduled=$(date -d @$time_scheduled +%Y/%m/%d)
1133 |
1134 | # Remove "🔔 " from the name
1135 | name_without_bell=${name//"🔔 "/}
1136 |
1137 | # Update the entries in INPUT_FILE
1138 | awk -v date="$time_scheduled" -v name="${name}" -v new_name="${name_without_bell}" '
1139 | BEGIN {OFS = FS = " "}
1140 | $1 == date && $0 ~ name {$0 = gensub(name, new_name, 1)} 1' $INPUT_FILE > tempfile && mv tempfile $INPUT_FILE
1141 |
1142 | # Delete the entry from the defaults array
1143 | unset "defaults[reminders[$i]]"
1144 |
1145 | # Delete the entry from the JSON file
1146 | jq --argjson pid ${pid} 'del(.reminders[] | select(.pid == $pid))' ${SETTINGS} > temp.json && mv temp.json ${SETTINGS}
1147 | fi
1148 | fi
1149 | done
1150 | }
1151 |
1152 |
1153 | # Google Calendar integration
1154 | gca_init() {
1155 | src_gca=0
1156 | declare -a outdated_index=()
1157 | declare -a outdated_names=()
1158 | declare -a outdated_categories=()
1159 | for (( i=0; i<${num_gca}; i++ )); do
1160 | end_year=${defaults["gca[$i][end_date]"]:0:4}
1161 | if [[ ${end_year} -lt $((year+1)) ]]; then
1162 | if [[ ${src_gca} -eq 0 ]]; then
1163 | source ${SCRIPTPATH}/${API}/gca.sh
1164 | src_gca=1
1165 | fi
1166 | outdated_index+=("${i}")
1167 | outdated_names+=("${defaults["gca[$i][name]"]}")
1168 | outdated_categories+=("${defaults["gca[$i][category]"]}")
1169 | fi
1170 | done
1171 |
1172 | if [[ ${#outdated_names[@]} -gt 0 && -z $1 ]] || [[ "${1^^}" == "UPDATE" ]]; then
1173 | [[ ${src_gca} -eq 0 ]] && source ${SCRIPTPATH}/${API}/gca.sh
1174 | src_gca=1
1175 | gca_auto_update &
1176 | echo "Google Calendar: Update may take awhile, please be patient..."
1177 | echo
1178 | elif [[ (( -z ${gca_skip} || ${gca_skip} -eq 0 ) && -z $1 ) || "${1^^}" == "IMPORT" ]]; then
1179 | [[ ${src_gca} -eq 0 ]] && source ${SCRIPTPATH}/${API}/gca.sh
1180 | src_gca=1
1181 | gca
1182 | if [[ "${choice^^}" != "X" ]]; then
1183 | echo "Google Calendar: Operation completed."
1184 | echo
1185 | fi
1186 | fi
1187 | }
1188 |
1189 |
1190 | # Yes/No selection
1191 | yes_no() {
1192 | echo -en "\n${1} [Y/n] "
1193 | read input_yn
1194 | case $input_yn in
1195 | [yY][eE][sS]|[yY]|"")
1196 | # Update the last execution date for this use case
1197 | user_input="yes"
1198 | ;;
1199 | *)
1200 | user_input=""
1201 | ;;
1202 | esac
1203 | }
1204 |
--------------------------------------------------------------------------------