#! /usr/bin/perl

$max_rss_items = 15;
$rssfile = "rss.rdf";

$lang = "ja";
$rssurl = "http://tombo.sourceforge.jp/tombo.rdf";
$toppage = "http://tombo.sourceforge.jp";
$description = "メモ管理ツールTOMBO リリース情報、お知らせ等を提供しています";

if ($#ARGV != 0 || !-d $ARGV[0]) {
    print "Usage : rssgen.pl <TMPLDIR>\n";
    exit 1;
}

$srcdir = $ARGV[0];

opendir(DIR, "$srcdir/news") || die;
my @l = sort( { $b <=> $a } readdir(DIR));
closedir(DIR);


my @items = ();


my $f, $d, $t, $sec, $headline, $cat, $dum;
my $i = 0;
foreach $f (@l) {
    next if ($f eq "." || $f eq "..");
    next unless ($f =~ /^([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})\.txt$/);
    last if ($i > $max_rss_items);

    $d = "$1-$2-$3";
    $t = "$4:$5";
    $sec = "$1$2$3$4$5";
    
    open(F, "$srcdir/news/$f") || die;
    
    $headline = <F>;
    chop($headline);
    
    $cat = <F>; chop($cat); # category
    $dum = <F>; # skip blank line

    $desc = "";
    while(<F>) {
	$desc .= $_;
    }
    close(F);

    my @itm = ($d, $t, $sec, $headline, $desc, $cat);
    push(@items, \@itm);

    $i++;
}

foreach $i (@items) {
    ($d, $t, $sec, $headline, $desc, $cat) = @{$i};
#    print "$d $t $sec $headline \n";
}


open(RSS, "| nkf -w > $srcdir/$rssfile") || die;
print RSS <<BASE ;
<?xml version="1.0" encoding="utf-8" ?>
<rdf:RDF
  xmlns="http://purl.org/rss/1.0/"
  xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" 
  xmlns:dc="http://purl.org/dc/elements/1.1/"
  xml:lang="$lang">
 
<channel rdf:about="$rssurl">
 <title>TOMBO announce</title>
 <link>$toppage</link>
 <description>$description</description>
 <items>
   <rdf:Seq>
BASE

foreach $i (@items) {
    ($d, $t, $sec, $headline, $desc, $cat) = @{$i};
    print RSS "    <rdf:li rdf:resource=\"$toppage/history.html#$sec\"/>\n";
}

print RSS "   </rdf:Seq>\n";
print RSS " </items>\n";
print RSS "</channel>\n";

foreach $i (@items) {
    ($d, $t, $sec, $headline, $desc, $cat) = @{$i};
    print RSS "<item rdf:about=\"$toppage/history.html#$sec\">\n";
    print RSS "  <title>$headline</title>\n";
    print RSS "  <link>$toppage/history.html#$sec</link>\n";
    print RSS "  <description>\n";
    print RSS $desc;
    print RSS "  </description>\n";
    print RSS "  <dc:date>$d"."T$t:00+09:00</dc:date>\n";
    print RSS "  <dc:subject>$cat</dc:subject>\n";
    print RSS "</item>\n";
}

print RSS "</rdf:RDF>\n";

close(RSS);
