#!/bin/bash
#                       /usr/local/bin/events
# https://crystalfaeries.net/posix/bin/events
# celeste:crystalfaery EVENTS 2021-02-25 04:26:49+00:00
# search our calendar for the next events

let help=6 # this line's number - 1

case $# in
0)	# we have no options nor arguments
cd	# there's no place like Om.
let DAYS=0 # try for automatic today or weekend:
/usr/bin/calendar >	/tmp/$$.txt
# Search forward in time for next calendar events:
until [ -s  /tmp/$$.txt ]
do	# progressively scan beyond today or weekend for next event:
	let DAYS=$DAYS+1
	/usr/bin/calendar -l $DAYS > /tmp/$$.txt
	let exitval=$?; if [[ $exitval -ne 0 ]] ; then break ; fi
	if [ 365 -lt   $DAYS ]
	then # our calendar has no pending events this year
    		echo "12/31	New Year's Eve" >> $HOME/.calendar/calendar
    		echo "12/31	New Year's Eve" > /tmp/$$.txt
	fi
done

# Sort the calendar events:
sort 	/tmp/$$.txt >		/tmp/$$.sorted.txt

# Output the calendar events expanding escape sequences
while [ -s			/tmp/$$.sorted.txt ]
do
	echo -e "$(head -n 1	/tmp/$$.sorted.txt)"	2>/dev/null
	tail -n +2		/tmp/$$.sorted.txt	2>/dev/null > /tmp/.$$.txt
	mv	/tmp/.$$.txt	/tmp/$$.sorted.txt
done	|	sed 's/\*	/	/;s/		/	/g'

# Append the Tri-Weekly events:
NOWYEAR="$(date +%Y)-"
for f in "${HOME}"/.calendar/.*.triweekly.txt
do
	FILEDATE="$(echo -e "$(date -r "${HOME}"/.calendar/.*.triweekly.txt +%s) + 1814400" | bc)"
	EVENTDATE="$(date --rfc-3339=date --date="@${FILEDATE}" | sed "s/^${NOWYEAR}//;s/-/\//")"
	echo -e "${EVENTDATE}	TriWeekly $(basename ${f}|sed 's/^\.//;s/\.triweekly\.txt$//')"	\
	>>	$HOME/.calendar/calendar
done
sort -n		$HOME/.calendar/calendar			>	$HOME/.calendar/calendar-
grep	'LANG='	$HOME/.calendar/calendar-	|	uniq	>	$HOME/.calendar/calendar
grep -v	'LANG='	$HOME/.calendar/calendar-	|	uniq	>>	$HOME/.calendar/calendar

rm	/tmp/.$$.txt /tmp/$$.txt /tmp/$$.sorted.txt	2>/dev/null
exit	$?
;;
*)	# we have an option or an argument of a date (not defaulting to today)
    case "${1}" in
    -v | --version)
	    head -n 4 $0 | tail -n 1
	    exit
	    ;;
    -h | --help)
	    head -n ${help} $0
	    exit
	    ;;
    *)	# the supplied single argument should be a date to check in the calendar file for events
	# NOTE: THAT calendar ONLY WORKS FOR THIS YEAR, so we should not be accepting other years as argument!
calendar -t $(date -u --rfc-3339=seconds -d "${1}" | sed 's/:[0-9][0-9]+00:00// ; s/ //g ; s/:// ; s/-//g ; s/[0-9][0-9][0-9][0-9]$//')	\
|	sed 's/\*	/	/' | sort -n
	;;
    esac
;;
esac
