#!/usr/bin/perl
#
# daily_calendar 1.5
#
# Call the calendar program for each day from the timestamp
# found in $HOME/calendar/.daily_calendar until today.
#

use strict;

my ($timestamp,
    $last_timestamp,
    $current_time);

# Location of the calendar file
chdir("$ENV{'HOME'}/calendar");

# Get the current time
$current_time = time();

# Read the timestamp file or create it
if (!open(TIMESTAMP, "< .daily_calendar"))
{
    # Set the timestamp value to the current time
    $timestamp = $current_time;

    if (!open(TIMESTAMP, "> .daily_calendar"))
    {
        die "Could not create .daily_calendar file\n";
    }
    else
    {
        print TIMESTAMP $timestamp;
    }
}
else
{
    $timestamp = <TIMESTAMP>;
    chomp($timestamp);

    # Advance the timestamp forward one day
    $timestamp += 86400;
}

# Let's not operate on a time in the future
if ($timestamp > $current_time)
{
    $timestamp = $current_time;
}

$last_timestamp = 0;
while($timestamp <= $current_time)
{
    system("calendar $timestamp");
    $last_timestamp = $timestamp;
    $timestamp += 86400;
}

my ($c_sec,$c_min,$c_hour,$c_mday,$c_mon,$c_year,$c_wday,$c_yday) =
                                                localtime($current_time);

my ($l_sec,$l_min,$l_hour,$l_mday,$l_mon,$l_year,$l_wday,$l_yday) =
                                                localtime($last_timestamp);

# Just in case we have a case where the timestamp is less than a
# day apart (which is likely), let's check to see if we covered the
# current day.  If not, we'll call calendar with the current time.
if ($l_mday != $c_mday)
{
    system("calendar $current_time");
}

# Now write out the current time
if (!open(TIMESTAMP, "> .daily_calendar"))
{
    die "Could not write to .daily_calendar file\n";
}
else
{
    print TIMESTAMP $current_time;
}
