#!/usr/bin/perl

#
#	calscript.pl
#
#	Usage:  calscript <email addr> <cal file>
#
#	This file reads a simple "cal file" and if the date
#	of an item has passed, that item is sent to the given 
#	email address.
#
#	For example, calscript yourname@server mycal
#	
#	will send email to yourname@server
#
#
#	Note:  	This script is made much more useful when it is
#		called automatically early in the morning by, 
#		for example, the following line in a crontab file:
#
#		00 6 * * * /yourdir/calscript.pl yourname@server /yourdir/cal
#
#
#	----------------------------------------------
#	Example "cal file"  -- Note that entries with
#			*w, *m or *y will be replaced
#			as they pass with the same 
#			entry occurring weekly, monthly
#			or annually.
#
#			A blank line separates entries.
#	----------------------------------------------
#
#	Mar 2, 2003
#	Meet with accountant to discuss taxes.
#
#	Jan 1, 2004 *y
#	New Year's - Have a party!
#
#	Feb 15, 2003 *m
#	Monthly Rent is Due
#
#	March 28, 2003 *w
#	Friday today - have a party!
#
#	----------------------------------------------
#
# =========== GET Command Line Arguments  ===========
$err = 0;
@monthname = ("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec","Jan");

if (@ARGV)
	{
	$emailaddr = shift (@ARGV);
	}

if (@ARGV)
    {

    $calfilename = shift (@ARGV);
    if (@ARGV)
    	{
	$calfileold = shift(@ARGV);
	}
    else
    	{
	$calfileold = $calfilename . ".old";
	}

    if (@ARGV)
    	{
	$calfilenew = shift(@ARGV);
	}
    else
    	{
	$calfilenew = $calfilename . ".new";
	}
    }
else
    {
    print("Usage:  calscript <email addr> <cal file> \n");
    $err = 1;
    }

    #print("Email = $emailaddr, oldfile = $calfileold, newfile = $calfilenew\n");


if ($err eq 0)
  {
	  # ========== OPEN FILES =============
	  #
  $noerr = (defined(open(CALFILE,$calfilename)));
  if ($noerr)
  	{
  	$noerr = (defined(open(NEWCALFILE,">$calfilenew")));
	}
  if ($noerr)
  	{
  	$noerr = (defined(open(OLDCALFILE,">>$calfileold")));
	}
  if ($noerr)
    {
    $line = <CALFILE>;

    while (defined($line))
    	{
	if ($line =~ /\S/ )
		{
		@daycomp = DayCompare($line);
		$ldc = scalar(@daycomp);
		$notpassed = shift(@daycomp);
		$month=shift(@daycomp);
		$day=shift(@daycomp);
		$year=shift(@daycomp);

		#print("DayComp($ldc) = $notpassed  ($month/$day/$year) \n");

		if ($notpassed < 1)		# Send it by email.
			{
				#print("Day passed.\n");
			if ($line =~ /\*([w|m|y])/)
				{
				$reptype=$1;
				$repeat = 1;
				if ($reptype =~ /^m/)
					{
					$newyear = $year;
					$newday = $day;
					if ($month > 11)
						{
					 	$newmonth=$monthname[0];
						$newyear = $year+1;
						}
					else
						{
				        	$newmonth = $monthname[$month];
						}
					}
				if ($reptype =~ /^y/)
					{
				        $newmonth = $monthname[$month-1];
					$newyear = $year+1;
					$newday = $day;
					}

				if ($reptype =~ /^w/)
					{
					$newyear = $year;
					$newday = $day+7;
					(@daysinmonth) = (31,28,31,30,31,30,31,31,30,31,30,31);
					if ($newday > $daysinmonth[$month])
						{
						$newday = $newday - $daysinmonth[$month];
						$month = $month + 1;
						if ($month > 12)
							{
							$month = 1;
							$newyear = $year+1;
							}
						}
				        $newmonth = $monthname[$month-1];
					}

				print NEWCALFILE ("$newmonth $newday, $newyear \*$reptype  \n");
				}
			else
				{
				$repeat=0;
				}	
			print OLDCALFILE ("$line");
			$line1 = $line;

			if (open(MAILFILE,"| /usr/lib/sendmail $emailaddr"))
			  

			
			    {
    			    $line = <CALFILE>;
			    print MAILFILE ("From:  $emailaddr\n");
			    print MAILFILE ("To:  $emailaddr\n");
			    print MAILFILE ("Subject:  *** Calendar: $line *** \n");
			    print MAILFILE ("$line1");

  			    while ($line =~ /\S/ )
    				{
				print OLDCALFILE ("$line");
				if ($repeat eq 1)
					{
					print NEWCALFILE ("$line");
					}
				print MAILFILE ("$line");
    				$line = <CALFILE>;
				}
				print OLDCALFILE ("\n");
				if ($repeat eq 1)
					{
					print NEWCALFILE ("\n");
					}
				close(MAILFILE);
			        }
			    else
			    	{
				print("Error opening output to email.\n");
				$line = "";
				$err = 1;
				}
			}



		else	# ============ Keep Date in NEW file ==========
			{
			while ($line =~ /\S/ )
    				{
					#print("Day not passed.\n");
				print NEWCALFILE ("$line");
    				$line = <CALFILE>;
				}
			print NEWCALFILE ("\n");
			}
		}

	else		# ============ Skip Over Blank Lines ===========

		{
			#print("Line was blank. \n");
			#print NEWCALFILE (".$line");
		$line = <CALFILE>;
		}
	}
    close(CALFILE);
    close(NEWCALFILE);
    close(OLDCALFILE);
    $closed = 1;
    }
  else
    {
    $err = 1;
    }
  }

if ($err < 1)
    {
    if ($closed eq 1)
	{
	$syscommand = "mv" . " " . $calfilenew . " " . $calfilename;
	system($syscommand);
	#print("$syscommand \n");
	}
    }







sub DayCompare
#
#	Function takes a date of the form   Jan 5, 2000.
#	Returns -1 if the date has passed, 0 if it is today, or 1 if still
#	to come.
#
#	INPUT:
#		0) - String of the form "Jan 5, 2000".
#			Comma is optional, space is not.  
#			"Jan" could be full word.
#
#	OUTPUT:
#		0) - -1, 0, 1 if passed, today or future.
#		     -2 if we can't tell.
#
	{
	my($month)="";
	my($day)="";
	my($year)="";

	if ($_[0] =~ /([A-Za-z]+)\s+([0-9]+).*\s+([0-9][0-9]+)/ )
		{	
		$month = MonthNum($1);
		$day = $2;
		$year = $3;

		#print("Date is (M/D/Y)  $month/$day/$year \n");

		if (scalar($year) < 90)
			{
			$year += 2000;
			}
		if (scalar($year) < 1900)
			{
			$year += 1900;
			}

		my($thismonth) = (localtime)[4] + 1;
		my($thisday) = (localtime)[3];
		my($thisyear) = (localtime)[5]+1900;

		if ($year < $thisyear)
			{
			$retval=-1;
			}
		if ($year > $thisyear)
			{
			$retval=1;	
			}
		if ($year == $thisyear)
			{
			if ($month < $thismonth)
				{
				$retval=-1;
				}
			if ($month > $thismonth)
				{
				$retval=1;
				}
			if ($month == $thismonth)
				{
				if ($day < $thisday)
					{
					$retval=-1;
					}
				if ($day > $thisday)
					{
					$retval=1;
					}
				if ($day == $thisday)
					{
					$retval=0;
					}
	
				}
			}
		}
	else
		{
		$retval = -2;
		}

	@actretval = $retval;
	#push(@actretval,$retval);
	push(@actretval,$month);
	push(@actretval,$day);
	push(@actretval,$year);

	#print("$retval, $month, $day, $year\n");
	return (@actretval);
	}



sub MonthNum
#
#	Function takes a month name (string) and returns
#	the month number (1-12).
#
#
#	INPUT:
#		0) - String containing month name.
#
#	OUTPUT:
#		0) - Month number.  (0 if not recognized.)
#

	{
	my($count);
	my(@months) = ("jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec");

	$retval = 0;

	for ($count=0; $count<12; $count++)
		{
		$mon = $months[$count];
		if ($_[0] =~/$mon/i  )
			{
			$retval = $count+1;
			}	
		}
	return($retval);
	}








