#!/usr/bin/perl -wa
# Copyright 2005 - Robin H. Johnson <robbat2@orbis-terrarum.net> 
use warnings;
use strict;
require XML::DOM;
require XML::XQL;
require XML::XQL::DOM;

my %CONF;
$CONF{'livejournal-robbat2'} = {	
	'url' => 'http://www.livejournal.com/users/robbat2/data/rss',
	'outputfile' => '/var/www/orbis-terrarum.net/www/robbat2-livejournal-gentoo-rss.xml',
	'querybase' => '/rss/channel/',
	# include all of the following elements always
	'common' => [ 'title', 'link', 'description', 'lastBuildDate', 'generator', 'image' ],
	# my filtering
	# XQL is fussy about ' vs. "
	# it will NOT take ".
	# you MUST use '.
	'filter' => [	"item[title =~ '/^Gentoo:/']",
					"item[title =~ '/XXS1500/']"
				]
};


sub grabdata {
	my $datasrc = shift;
	my $parentnode = shift;
	my $query = shift;
	my @results = $datasrc->xql($query);
	foreach my $node (@results) {
		my $newnode = $node->cloneNode(1);
		$newnode->setOwnerDocument($parentnode->getOwnerDocument);
		$parentnode->appendChild($newnode);
	}
}

foreach my $key (keys %CONF) {
	my $newdoc = new XML::DOM::Document;
	my $rss = $newdoc->createElement('rss');
	$rss->setAttribute('version','2.0');

	#print 'Key: '.$key."\n";
	my $url = $CONF{$key}{'url'};
	#print 'URL: '.$url."\n";
	my $parser = new XML::DOM::Parser;
	my $doc = $parser->parsefile($url);
	my $channel = $newdoc->createElement('channel');
	$rss->appendChild($channel);

	my @d = @{$CONF{$key}{'common'}};
	push @d,@{$CONF{$key}{'filter'}};
	
	my $querybase = $CONF{$key}{'querybase'};
	foreach my $query(@d) {
		$query = $querybase.$query;
		#print 'XQL: '.$query."\n";
		grabdata($doc,$channel,$query);
	}
	$rss->printToFile($CONF{$key}{'outputfile'});
	$rss->dispose;
}
