#!/bin/bash
#                       /usr/local/bin/events
# https://crystalfaeries.net/posix/bin/events
# celeste:crystalfaery EVENTS 2021-03-07 15:18:26+00:00
# search our calendar for the next events
let help=5 # this line's number - 1

cd	"${HOME}" || exit -1
case $# in
0)	# we have no options nor arguments
	:
	;;
*)	# we have an option
    case "${1}" in
    -v | --version)
	    head -n 4 $0 | tail -n 1
	    exit
	    ;;
    -h | --help)
	    head -n ${help} $0
	    exit
	    ;;
    *)	echo "$0 does not cognize $@" >&2
	exit -2
	;;
    esac
    ;;
esac

# Search forward in time for next calendar events:
for DAYS in {0..365}
do
	/usr/bin/calendar -f "${HOME}"/.calendar/calendar -l $DAYS \
					>	/tmp/$$.txt
	if [ -s					/tmp/$$.txt ]
	then

		# Sort the calendar events:
		sort -n			  	/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'

#		rm	/tmp/.$$.txt /tmp/$$.txt /tmp/$$.sorted.txt	2>/dev/null
		exit	$?
	fi
done
exit	$?
