#!/usr/bin/perl
use 5.016;
use strict;
use warnings;

use List::Util qw(any);
use POSIX qw(strftime);

use constant {
    SUN => 0,
    MON => 1,
    TUE => 2,
    WED => 3,
    THU => 4,
    FRI => 5,
    SAT => 6,
};

my $DAY = 60 * 60 * 24;

my $ATOM_TIME_FMT = '%Y-%m-%dT%H:%M:%SZ';

my $HOSTNAME = qx`hostname -f` =~ s/\n$//r;
my $WHOAMI   = qx`whoami` =~ s/\n$//r;

my $TITLE     = "$WHOAMI\'s system reminders";
my $SUBTITLE  = "Atom feed for various system reminders.";
my $SELF_LINK = "file://$0";
my $LINK      = $HOSTNAME;
my $ID        = "$HOSTNAME:reminders";
my $AUTHOR    = $WHOAMI;

my $now = time;
my $now_fmt = strftime($ATOM_TIME_FMT, localtime $now);

my @reminders = (
    {
        title   => sub { "... - $_[0]->{ date }" },
        id      => sub { "$ID/...:$_[0]->{ date }" },
        summary => sub { "... - $_[0]->{ date }" },
        days    => [ ... ],
        date    => undef,
    },
);

sub prev_day {

    my ($days) = @_;

    my $day = $now;

    until (any { $_ == (localtime($day))[6] } @$days) {
        $day -= $DAY;
    }

    return $day;

}

print <<"HERE";
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
    <title>$TITLE</title>
    <subtitle>$SUBTITLE</subtitle>
    <link href="$SELF_LINK" rel="self"/>
    <link href="$LINK"/>
    <id>$ID</id>
    <updated>$now_fmt</updated>
    <author><name>$AUTHOR</name></author>
HERE

for my $r (@reminders) {
    my $prev = prev_day($r->{ days });
    $r->{ date } = strftime($ATOM_TIME_FMT, 0, 0, 0, (localtime($prev))[3 .. 8]);
    $r->{ title } = $r->{ title }($r);
    $r->{ id } = $r->{ id }($r);
    $r->{ summary } = $r->{ summary }($r);
    print <<"HERE";
    <entry>
        <title>$r->{ title }</title>
        <id>$r->{ id }</id>
        <updated>$r->{ date }</updated>
        <summary>$r->{ summary }</summary>
    </entry>
HERE
}

print <<"HERE";
</feed>
HERE

1;

# vim: expandtab shiftwidth=4
