#!/usr/bin/perl
use XML::Feed;
use Text::CSV;
use POSIX qw(setsid);
use strict;

# Parameters are xmarks rss feed, foswiki file to be updated, xmarks temp file
my @parameters = ( [ "http://share.xmarks.com/folder/rss/I7UONAQ3ci",
		     "/var/www/egeland/foswiki/data/Main/SystemAdmin.txt",
		     "/var/tmp/primaryxmarks" ],
		   [ "http://share.xmarks.com/folder/rss/82YkFihdDm",
		     "/var/www/egeland/foswiki/data/Main/SecondarySoftware.txt",
		     "/var/tmp/secondaryxmarks" ]
    );

foreach my $array (@parameters) {
    my ($rss, $foswikifile, $xmarksfile) = @$array;

    # Read previously retrieved bookmarks file
    open FILE, $xmarksfile or die "Couldn't open file: $!"; 
    my $written = join("", <FILE>); 
    close FILE;
    
    my $newtext = &hashref2wiki(&xmarks2hashref($rss));
    if ( $written ne $newtext ) {
	&fileinsert($foswikifile,$newtext);
	# Save bookmarks to local file
	open FILE, ">$xmarksfile" or die "Couldn't open file: $!"; 
	print FILE $newtext;
	close FILE;
	$written = $newtext;
    }
}

sub xmarks2hashref { # Takes feedmarks rss url as argument
    my $feed = XML::Feed->parse(URI->new($_[0])); # or die XML::Feed->errstr;
    my %items;
    # Generating a hash of hashes
    die unless ($feed->entries);
    for my $entry ($feed->entries) {
	my %i;
	$i{title} = $entry->title;
	$i{link} = $entry->link;
	($i{desc}, $i{tags}) = split(/\s*Tags:\s*/,$entry->content->body);
	$i{desc} =~ s/\.$//g; # remove trailing period
	$items{"\L$i{title}"} =  \%i; # lowercased titles are keys
    }
    return \%items;
}

sub hashref2wiki { # Takes hashref as argument
    my %items = %{$_[0]};
    my $wiki;
    for my $key (sort keys(%items)) {
	$wiki .= "   * [[$items{$key}{link}][$items{$key}{title}]]. $items{$key}{desc}.\n";
    }
    $wiki =~ s/[^[:ascii:]]+//g; # Remove non-ASCII characters
    return $wiki;
}


sub fileinsert { # filename, wikitext as argument
    my ($filename, $wikitext) = @_;
    my $modified = "";
    open(IN, "$filename") or die "Can't open $filename!";
    my $n = 1; # Print file line?
    while (<IN>) {
	if ( $n eq 1 ) { $modified .= $_ }
	if (/^\<.*START/) { $modified .= $wikitext; $n = 0 }
	if (/^\<.*END/) { $modified .= $_ ; $n = 1 }
    }
    $modified .= "\n";
    close(IN);
    open(OUT, ">$filename") or die "Can't create $filename!";
    print OUT $modified;
    close(OUT);
    print "Wrote updates to $filename\n";
}
