#!/usr/bin/perl

# Announcements are read from dat/index.md; Each announcement must have the following format:
#   `$date` - $title $meta
#   :    $body
#
# The $meta and $body are optional. $meta must be in the form:
#   <!-- $fields --> or <!- $fields ->
#
# $fields can be:
#   tags: comma-separated list of tags, these are used to determine whether an
#         announcement belongs to a particular feed.
#   link: Path that the announcement should link to, absent = '/'

use TUWF::XML ':xml';
use POSIX 'strftime';
use IPC::Open2;

$sub = (shift =~ m{pub/(?:([^/]+)/)?feed.atom} ? $1 : '');

$/=undef;
my $body = <>;
my @annuncements;
while($body =~ /`([0-9]{4}-[0-9]{2}-[0-9]{2})` - ([^\n]+)\n(:   .+\n(?:\n|    .+\n)*)?/mg) {
    my($date, $title, $data) = ($1,$2,$3);
    $data =~ s/^:/ /;
    $data =~ s/^    //mg;
    $data =~ s/\s+$//;
    $meta = $title =~ s/ *<!--? (.+) -?->$// ? $1 : '';
    $tags = 
    $link = $meta =~ /link:([^:]+)/ ? $1 : '';
    push @announcements, {
        date  => $date,
        title => $title,
        body  => $data,
        tags  => $meta =~ /tags:([^:]+)/ ? $1 : '',
        link  => $meta =~ /link: *([^: ]+)/ ? $1 : '',
    };
}


$self = 'https://dev.yorhel.nl/' . ($sub ? "$sub/" : ''). 'feed.atom';
TUWF::XML->new(default => 1, pretty => 2);
xml;
tag feed => xmlns => 'http://www.w3.org/2005/Atom', 'xml:lang' => 'en', 'xml:base' => 'https://dev.yorhel.nl/', sub {
    tag title => $sub ? "\u$sub Project Announcements" : "Yorhel's Projects";
    tag updated => strftime('%Y-%m-%dT%H:%M:%SZ', gmtime time);
    tag id => $self;
    tag link => rel => 'self', type => 'application/atom+xml', href => $self, undef;
    tag link => rel => 'alternate', type => 'text/html', href => 'https://dev.yorhel.nl/'.$sub, undef;

    for(@announcements) {
        next if $sub && $_->{tags} !~ /\Q$sub/;
        last if $n++ >= 10;
        my $url = 'https://dev.yorhel.nl'. ($_->{link} || '/') . ($_->{link} =~ /#/ ? '' : "#$_->{date}");
        tag 'entry', sub {
            tag id => $url;
            tag title => $_->{title};
            tag updated => $_->{date}.'T12:00:00Z';
            tag published => $_->{date}.'T12:00:00Z';
            tag 'author', sub {
                tag name => 'Yoran Heling';
                tag uri => 'https://dev.yorhel.nl/';
                tag email => 'projects@yorhel.nl';
            };
            if($_->{body}) {
                open2 $OUT, $IN, qw/pandoc -f markdown -t html/;
                print $IN $_->{body};
                close $IN;
                ($html = <$OUT>) =~ s{href="/}{href="https://dev.yorhel.nl/}g; # Absolute URLs
                tag 'summary', type => 'html', $html;
            }
            tag link => rel => 'alternate', type => 'text/html', href => $url, undef;
        };
    }
}
