#!/usr/bin/perl

# remindertron 0.1
#
# Copyright 2002 Nathan J. Mehl
# released under the terms of the GNU General Public License v2.0
#
# run this out of cron to be reminded at regular intervals of upcoming
# yearly events such as birthdays and anniverseries
#
# datafile format:
#
# Name:Event Type:DD:MM[:YYYY]
#
# for example:
#
# Wendy Testaburger:birthday:28:11:1978
# Joe Testaburger:birthday:4:09
# Your Marriage:anniversary:18:08:1965
# High School Class:reunion:5:7
# 
# Years can be two or four digits, but don't get cute
#

use Date::Calc qw(:all);
#use Data::Dumper;

$DATAFILE="/home/memory/etc/birthdays.txt";
$EMAIL="memory\@blank.org";

($THISYEAR,$THISMONTH,$THISDAY) = Today;
$NEXTYEAR= $THISYEAR + 1;
$DAY = Date_to_Days($THISYEAR,$THISMONTH,$THISDAY);
$NDAY = Date_to_Days($NEXTYEAR,$THISMONTH,$THISDAY);

open(BDAYS,"<$DATAFILE") || die "couldn't open $DATAFILE";

while(<BDAYS>){

	next if /^\#/;
	chomp;

	my ($Bname,$Btype,$Bday,$Bmonth,$Byear) = split(/:/);
	if ( $Byear =~ /^[0-9][0-9]$/ ) {
		$Byear = Fixed_Window($Byear);
	} elsif ( $Byear =~ /^$/ ) {
		$Byear = "none";
	}
	
	my $bday = Date_to_Days($THISYEAR,$Bmonth,$Bday);
	my $Nbday = Date_to_Days($NEXTYEAR,$Bmonth,$Bday);

	my $remain = $bday - $DAY;
	my $Nremain = $Nbday - $DAY;
	my $Ryear = $THISYEAR;

	if ( $remain < 0 ) { 
		$remain = $Nremain; 
		$Ryear++;
	}

	#print "DEBUG: Next $Btype for $Bname in $remain days.  Born in $Byear\n";

	if ( $remain < 8 ) {
		my $bline = $remain . ":" . $Btype . ":" . $Byear .  ":" . $Bname . ":" . $Ryear;
		push @BLINES, $bline;
	}

}

# sort the damn thing first by days remaining

@BLINES = sort {
	($a =~ /^(\w+):/)[0] <=> ($b =~ /^(\w+):/)[0]
} @BLINES;

$THISDAY = English_Ordinal($THISDAY);
$THISMONTH = Month_to_Text($THISMONTH);

#print "DEBUG:" . Dumper(@BLINES);

if ( @BLINES ) {

#open(OUTFILE,'>-');
open(OUTFILE,"|/usr/bin/Mail -s \"REMINDERTRON ALERT\" $EMAIL");

print OUTFILE "\nToday is the $THISDAY of $THISMONTH, $THISYEAR.\n";
print OUTFILE "\n---\n";

	for (@BLINES) {
	
		my ($remain,$Btype,$Byear,$Bname,$Ryear) = split(/:/);
	
		my $age = $Ryear - $Byear unless ( $Byear eq "none");
		if ( defined($age))  {
			$age = English_Ordinal($age); 
		}
		
		if ( $remain == 0 ) {
			print OUTFILE "\n**** TODAY is $Bname\'s $age $Btype\!  Hope you sent them a card!\n";
		} elsif ( $remain == 1 ) {
			print OUTFILE "\n*** $Bname\'s $age $Btype is TOMORROW! You sent them a card, right?\n";
		} elsif ( $remain =~ /[23]/ ) {
			print OUTFILE "\n** $Bname\'s $age $Btype is in $remain days!\n";
		} elsif ( $remain == 7 ) {
			print OUTFILE "\n* $Bname\'s $age $Btype is in one week.  Time to send them a card!\n";
		}
	}

}

close(OUTFILE);

