#!/usr/bin/perl -w
use strict;
use warnings;
use File::Basename;
use Getopt::Std;
use HTML::Entities;
use LWP::Simple qw(get);
use Template::Extract;
use Text::Wrap qw(wrap 72);

my %opts;
getopts('lr', \%opts);

# sanity check that we didn't get both options
die basename($0), ":  [ -l (latest quotes) | -r (random selection) ]\n"
  if ($opts{'r'} && $opts{'l'});


my $query_param = $opts{'r'} ? "random" : "latest";
my $base_url = 'http://www.bash.org/?';
my $extract = Template::Extract->new();


# try and get the page of quotes
my $document = get "$base_url$query_param"
  or die "Failed to get quote page.";


# define the quote extraction temlpate
my $template = << 'END_OF_TEMPLATE';
[% FOR quotes %]
<p class="quote"><a href="?[% quote_num %]"
[% ... %]
<p class="qt">[% quote_text %]</p>
[% END %]
END_OF_TEMPLATE


# try and parse the quotes out.
my $data = $extract->extract($template, $document);


for (@{$extract->extract($template, $document)->{quotes}}) {

  # make the text presentable.
  $_->{quote_text} =~ s!<br />!!g;
  my $quote = decode_entities($_->{quote_text});

  # if you don't like the output format change this code
  print wrap('', '', $quote), "\n\n"; # the text of the quote
  print " -- Quote Num: ", $_->{quote_num};
  print "  ::  Original Location: $base_url$_->{quote_num}\n";
  print "\n---------------------\n\n"; # quote delimiter
}
