The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.
#!/usr/bin/perl
use strict;
use warnings;
use Socialtext::Resting::Getopt qw/get_rester/;

my $r = get_rester();
my $most_wanted_page = 'Most Wanted Pages';

warn "Fetching all pages...\n";
my @all_pages = $r->get_pages();
my %most_wanted;
my %wanters;
for my $page (@all_pages) {
    next if $page eq $most_wanted_page;
    warn "Fetching '$page'\n";
    my @incipient = $r->get_frontlinks($page, 1);
    for my $i (@incipient) {
        $wanters{$page}++;
        push @{ $most_wanted{$i} }, $page;
    }
}

warn "Creating most wanted page...\n";
my $incipient_page_count = keys %most_wanted;
my $now = localtime;
my $page_wanters_count = keys %wanters;
my $new_page = "^^ Most Wanted Pages in " . $r->workspace . " at $now.\n"
             . "There are $incipient_page_count pages wanted by $page_wanters_count other pages.\n"
             . "This page is autogenerated by `stu-most-wanted`, from \"Socialtext-Resting-Utils\" "
             . "<http://search.cpan.org/dist/Socialtext-Resting-Utils>\n\n"
             . "| *Wanted Page* | *Count* | *Wanters* |\n";

my $max_most_wanted = 100;
for my $i ( sort { @{ $most_wanted{$b} } <=> @{ $most_wanted{$a} } }
            keys %most_wanted ) {
    $new_page .= "| [$i] | " . @{ $most_wanted{$i} } . " | "
               . join(", ", map { "{{[$_]}}" } @{ $most_wanted{$i} })
               . " |\n";
    $max_most_wanted--;
    last if $max_most_wanted == 0;
}

# Check if the page has changed
my $page_name = 'Most Wanted Pages';
my $prev_page = strip_date_from_page($r->get_page($page_name));
my $new_page_dateless = strip_date_from_page($new_page);

if ($prev_page ne $new_page_dateless) {
    warn "Putting most wanted pages page...\n";
    $r->put_page($page_name, $new_page);
}
else {
    warn "Most wanted didn't change...\n";
}
exit;

sub strip_date_from_page {
    my $content = shift;
    $content =~ s/Most Wanted Pages in \S+ at [^.]+.//;
    return $content;
}