#!/usr/bin/perl

# Delicious Library exporter
# Copyright 2005 Evan Miller
# Do whatever you want with it.

use HTML::Template;
use HTML::Template::XPath;
use CGI qw/:standard/;

print <<EOF;
Delicious Export 0.1
Written in the copious free time of Evan Miller (06emm)

EOF

print STDERR "Location? ";
$location = <>;
chomp $location;

print STDERR "Your name? ";
$name = <>;
chomp $name;

print STDERR "Unix? ";
$unix = <>;
chomp $unix;

# Get variables from the user.
while (!$template) {
    print STDERR "books/music/movies? ";
    $type = <>;

    if ($type =~ /book/i) {
# The templates. Everything between the CONTENT_LOOP tags is repeated for each item.
	$template  = <<EOF;
<CONTENT_LOOP NAME="/library/items/book">|<CONTENT_VAR NAME="\@author">||<CONTENT_VAR NAME="\@title">||$location (<a href="http://wso.williams.edu/facebook/view?unix=$unix">$name</a>)
|-
</CONTENT_LOOP>
EOF
    }
    if ($type =~ /music/i) {
	$template  = <<EOF;
<CONTENT_LOOP NAME="/library/items/$type">|<CONTENT_VAR NAME="\@artist">||<CONTENT_VAR NAME="\@title">||$location (<a href="http://wso.williams.edu/facebook/view?unix=$unix">$name</a>)
|-
</CONTENT_LOOP>
EOF
    }
    if ($type =~ /movie/i) {
	$template  = <<EOF;
<CONTENT_LOOP NAME="/library/items/$type">|<CONTENT_VAR NAME="\@title">||$location (<a href="http://wso.williams.edu/facebook/view?unix=$unix">$name</a>)
|-
</CONTENT_LOOP>
EOF
    }
}

# Now interpolate the variables from the Delicious Library
# XML file into our little template above.
my $xpt = new HTML::Template::XPath(default_lang => 'en',
		root_dir => glob("~") . "/Library/Application Support/Delicious Library",
		relaxed_parser => 'yes' );
my $output = $xpt->process( xpt_scalarref => \$template,
		xml_filename => 'Library Media Data.xml',
		lang => 'en');

### clean up the formatting
# Remove subtitles
${$output} =~ s/ ?[(:].*?\|\|/\|\|/g;
# Remove leaving spaces
${$output} =~ s/[ \t]*\|\|/\|\|/g;
# change newline-separated authors to comma-separted authors
${$output} =~ s/(\w)\n(\w)/\1, \2/g;

# Finally, print to standard output.
print ${$output};
