#!/bin/ksh
#
# $Revision: 1.13 $ $Date: 2012-07-26 17:11:47-04 $
# $Source: /home/vogelke/bin/RCS/agenda,v $
# $Host: sys7.com $
# $UUID: 4b1734e0-ffb6-3c36-908d-46b94d954949 $
#
#<agenda: show reminders for today, tomorrow, and the day after.

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

dateprog=/usr/local/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) printf "\n%s\n", $0
                else print $0
                prev = $0
                k++
            }
        } else {
            if (length($0)) str[$0]++
            if (str[$0] == 1) print " *", $0
        }
    }
    '
}

# 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 today, tomorrow, and the day after.
# Any arguments will specify a single date, like 'last friday'.

case "$#" in
    0) arg='0 1 2' ;;
    *) 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

# Any TV shows?

echo; echo '------------------------------------'
grep -h pm $HOME/.calendar/????.rem |
    remind -h - $dmy | showme | sed -e 's/Reminders/TV/'

exit 0
