#!/usr/bin/perl

# Public domain as in http://en.wikipedia.org/wiki/Public_domain

# Originally written by David Moreno Garza <damog@damog.net>,
#  dedicated to Ana Isabel, mi gordita de requesón con salsa de 
#  chile de árbol.

use strict;
use warnings;

use WWW::Mechanize;
use LWP::Simple;
use Gnome2::GConf;

my $wallpaper_site = 'http://wallpaper.deviantart.com/';
my $favourites_text = qq{Browse Today's Favourites};
my $gconf = Gnome2::GConf::Client->get_default;
my $gconf_key = '/desktop/gnome/background/picture_filename';

print "- Iniciando...\n";

my $dev = WWW::Mechanize->new(agent => 'deviantart-perl random/gnome/wallpaper 0.0.1');
$dev->get($wallpaper_site);

$dev->follow_link(text => $favourites_text) or die "I couldn't find today's favourites: $!";

$dev->content =~ /<div class="dev\-100 dev\-4">(.*)<\!\-\-\[if IE\]>/s;
my $div = $1;

my @imgs;
my $i = -1;
foreach(split(/\n/, $div)) {
	$imgs[$i] = $1 if $_ =~ /"http\:\/\/www\.deviantart\.com\/deviation\/(.{8})\/"/;
	++$i;
}

my $rand = rand(@imgs);

$dev->get("http://www.deviantart.com/view/$imgs[$rand]");

my $wallpaper;
$wallpaper = $1 if $dev->content =~ m/<div class="trailing leading section\-block submission" id="deviation\-view">.*<img src="(.*)" width.*<div class="read notice trailing section\-block">/s;

print "- Voy a bajar $wallpaper...\n";

$wallpaper =~ /.*\/(.*)\.(.{3})$/;
my ($filename, $extension) = ($1, $2);

exec("mkdir ~/.deviantart") unless -e "$ENV{HOME}/.deviantart";
my $wallfile = "$ENV{HOME}/.deviantart/$filename.$extension";

print "- Guardando en $wallfile...";
getstore($wallpaper, $wallfile) or die($!);
print " Listo.\n";

$gconf->set_string($gconf_key, $wallfile) or die $!;

print "Done!\n";

syntax highlighted by Code2HTML, v. 0.9.1