#!/usr/bin/perl

use XML::Simple;

# update $HOME with your home directory
my $HOME   = "/home/mala";

my $BGFILE = "$HOME/.gnome2/backgrounds.xml";	# this is the file which contains BG config
my $PREFIX = "/desktop/gnome/background";	# this is the prefix of all the keys

my %mappings;
$mappings{'filename'} 	= 'picture_filename';	# mappings between cfg file and keys
$mappings{'options'} 	= 'picture_options';
$mappings{'shade_type'}	= 'color_shading_type';
$mappings{'pcolor'}	= 'primary_color';
$mappings{'scolor'}	= 'secondary_color';

# parse config file and extract wallpaper list
my $config = XMLin($BGFILE);
my $wp = $$config{'wallpaper'};

# extract a random background from the cfg file
my @bg = keys %$wp;
my $randombg;
do{
	$randombg = $$wp{@bg[int(rand(@bg))]};
}while ($$randombg{'filename'} eq '(none)' || $$randombg{'deleted'} eq 'true');
# (NOTE: this ignores deleted backgrounds and the ones without a wallpaper)

# apply changes
for (keys(%mappings)){
	my $cmd = "gconftool -t str -s $PREFIX/$mappings{$_} \"$$randombg{$_}\"";
	system($cmd);
}
