diff --git a/epsiEDTtoICS.sh b/epsiEDTtoICS.sh index 934331e..84d4117 100755 --- a/epsiEDTtoICS.sh +++ b/epsiEDTtoICS.sh @@ -64,6 +64,10 @@ function check_parameters_and_set_defaults() { log 2 "The directory (option -c or -p) “$(dirname "$OUTPUT")” is not writeable, or the filename is invalid" exit 2 fi + if [ -n "$PATCH" -a "$OUTPUT" != - ] && ! [ -f "$OUTPUT" -a -r "$OUTPUT" -a -w "$OUTPUT" ]; then + log 2 "Patching (option -p) needs an existing r/w file; this one is not: $OUTPUT" + exit 3 + fi if [ -n "$JOURNAL" ] && ! which systemd-cat >/dev/null; then JOURNAL= log 4 "Command “systemd-cat” not found" @@ -211,6 +215,30 @@ function output_ical_week { | html_week_to_ical_week "$1" "$2" } +# $1: offset (±) from today, to locate the week +function dump_known_ical_week { + local offsetDayOfWeek=$(date +%u -d "${1}days") # ∈ [1=monday … 5=friday] + local mon=$(date +%Y%m%d -d "$((${1}+1-$offsetDayOfWeek))days") + local tue=$(date +%Y%m%d -d "$((${1}+2-$offsetDayOfWeek))days") + local wed=$(date +%Y%m%d -d "$((${1}+3-$offsetDayOfWeek))days") + local thu=$(date +%Y%m%d -d "$((${1}+4-$offsetDayOfWeek))days") + local fri=$(date +%Y%m%d -d "$((${1}+5-$offsetDayOfWeek))days") + + tr -d '\r' <"$OUTPUT" \ + | awk -v week="^DTSTART:($mon|$tue|$wed|$thu|$fri)" ' + function out() { + if (inWeek==1) { + printf("%s", day) + inWeek=0 + } + } + /BEGIN:VEVENT/ { day=$0 "\n"; next } + { day=day $0 "\n" } + $0 ~ week { inWeek=1 } + /END:VEVENT/ { out() } + ' +} + # &1: first offset of the school-year, and max offset of the same school-year, space-separated function get_first_and_max_offset_of_year() { local currentYear=$(date +%Y) @@ -229,21 +257,46 @@ function get_first_and_max_offset_of_year() { printf '%s %s\n' $offset $offsetMax } +# $1: offset (±) from today, to locate the week +# exit status: 0 if $1 is in the current week +function is_current_week() { + local offsetWeek=$(date +%G%V -d "${1}days") + local currentWeek=$(date +%G%V) + [ $offsetWeek -eq $currentWeek ] +} + function main() { check_parameters_and_set_defaults { local dtstamp=$(date -u +%Y%m%dT%H%M%SZ) local offset= offsetMax= + local step=-1 # -1: before patching; 0: patching time-span; 1: after patching read -r offset offsetMax < <(get_first_and_max_offset_of_year) - if [ -n "$PATCH" ]; then - offset=0 - [ $MAXOFFSET -lt $offsetMax ] && offsetMax=$MAXOFFSET - fi output_ical_header while [ $offset -lt $offsetMax ]; do - output_ical_week $offset "$dtstamp" + if [ -n "$PATCH" ]; then + case $step in + -1) + if is_current_week $offset; then + MAXOFFSET=$((MAXOFFSET+offset)) + step=0 + continue + fi + dump_known_ical_week $offset ;; + 0) + if [ $offset -ge $MAXOFFSET ]; then + step=1 + continue + fi + output_ical_week $offset "$dtstamp" ;; + 1) + dump_known_ical_week $offset ;; + esac + else + output_ical_week $offset "$dtstamp" + fi offset=$(($offset+7)) done output_ical_footer