#!/bin/ksh
#<agenda: show reminders for today, tomorrow, and the day after.

PATH=/usr/local/bin:/usr/gnu/bin:/bin:/usr/bin
export PATH
umask 022

dateprog=/bin/date    # requires GNU version of date
notebook="$HOME/notebook"
special=

# Weed out duplicates, handle pretty-printing

showme () {
    awk '{
        if ($1 == "Reminders" && $2 == "for") {
            if ($0 != prev) {
                if (k > 0) new = sprintf("\n%s", $0)
                else new = $0
                prev = $0
                k++
            }
        } else {
            if (length($0)) str[$0]++
            if (str[$0] == 1) {
                if (length(new)) print new
                print " *", $0
                new = ""
            }
        }
    }
    '
}

# Look for special files.

# movie_file="$HOME/.calendar/movies.rem"
# test -f "$movie_file" && special="$special $movie_file"

other_dates="$HOME/.calendar/special.rem"
test -f "$other_dates" && special="$special $other_dates"

# Default: show reminders for the next two weeks.
# Any arguments will specify a single date, like 'last friday'.

case "$#" in
    0) arg="$(seq 0 14)" ;;
    *) arg=$($dateprog -d "$*" '+%d-%b-%Y') ;;
esac

# Daily agendas are in their own directories, usually without
# any days specified within the agenda file itself; therefore,
# we need to change "REM MSG" to show the date we're interested in.
#
# NOTE: use a day-counter plus "days 12am" to avoid interesting
# problems around Daylight Savings Time.

for day in $arg
do
    case "$day" in
        *-*) ;;                  # argument like "next tue".
          *) add="days 12am" ;;  # no arguments.
    esac

    set X $($dateprog -d "$day $add" "+%d %b %Y %Y/%m%d")
    shift
    dmy="$1 $2 $3"
    afile="$notebook/$4/agenda"

    (
      test -f "$afile" && sed -e "s/REM MSG/REM $dmy MSG/" $afile
      cat $special
    ) | remind -h - $dmy
done | showme

exit 0
