#!/usr/bin/perl -w
# ----------------------------------------------------------------------
#    Author  : Sbskl (Sébastien Groult) sbskl@sbskl.com
#    Date    : 2010-07-22
#    Version : 1.0.2
#
#    This program is free software; you can redistribute it and/or
#    modify it under the terms of version 2 of the GNU General Public
#    License as published by the Free Software Foundation.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
# ----------------------------------------------------------------------
use strict;

my $cmd = 'gconftool --set --type=string /desktop/gnome/background/picture_filename'; # Commande GNOME pour changer le papier peint
my $max = 1440; # 24x60min = 24h

die "
Usage : changewallpaper.pl ~/chemin minutes
	chemin  : Chemin vers les papiers peints
	minutes : Temps en minutes entre chaque changement\n
" if @ARGV != 2;
my( $path, $wait ) = @ARGV;

$path =~ s/\/$//; # Suppression du dernier slash s'il existe
$path =~ s/ /\\ /g; # Echappement des espaces
$wait = ( $wait < 1 ? 1 : ( $wait > $max ? $max : $wait ) ) * 60; # en secondes

print "$path\n";
# Parcours du répertoire à la recheche d'image
my %pictures;
while ( <$path/*> ) { $pictures{$_} = 0 if /\.jpg$/i; } # Du .jpg uniquement
print keys( %pictures )." images trouvées dans $path\n";

my $picture = '';
my $usedPictures = 0;

for ( srand( time( ) ); ; ) {

	# Récupération d'une image aléatoire différente de la précédente
	my $oldPicture = $picture;
	while ( %pictures ) {
		my $i = int(rand(keys %pictures));
		$picture = (keys %pictures)[$i];
		if ( -f $picture ) { last unless $picture eq $oldPicture or $pictures{$picture}; }
		else { --$usedPictures if $pictures{$picture}; delete $pictures{$picture}; print "$picture n'existe plus\n"; }
	}

	# Changement du papier peint
	if( %pictures ) {
		$pictures{$picture} = 1; # = Image utilisée
		print ++$usedPictures.'/'.keys(%pictures)." : Changement pour $picture\n";

		if ( $usedPictures == keys( %pictures ) ) { # Toutes les images ont déjà été utilisées
			# On remets les compteurs à zéro...
			for my $i ( keys %pictures ) { $pictures{$i} = 0; }
			$usedPictures = 0;
		}

		`$cmd "$picture"`;
	}

	# Attente
	print "Attente de ${wait}s...\n";
	sleep $wait;

	# Parcours de nouveau le répertoire à la recherche de nouvelles images...
	while ( <$path/*> ) { if ( /\.jpg/i and !defined($pictures{$_}) ) { $pictures{$_} = 0; print "Nouvelle image : $_\n"; } }
}

