#!/usr/bin/perl
# Author: 	2007 Patrick Winnertz <patrick.winnertz@skolelinux.org>
# 	 	2009 Holger Levsen <holger@debian.org>
# License: 	GPLv2 or later
#
# This small scripts downloads and stores the images in the images/ subdir, 
# then it modifies the xml file to use these images


use strict;
use warnings;
use IO::Dir;

our $base = "http://wiki.debian.org";
our $imagedir = "./images";
our $file = $ARGV[0];
our $path = $ARGV[1];


sub create ($) {
	my $link = shift;
	my $name = $link;
	my $url;
	# use regex to replace the long url with shorter one
	$name =~ s#$base/$path/\w+\?action=AttachFile&amp;do=get&amp;target=([\w\d]+)#$1#g;
	# special case the worldmap image
	if ($name =~ m#http://www\.skolelinux\.no/slschools/worldmap\.php\?lang=en&amp;image=worldmap\.png#) {
		$url = $name;
		$name = "worldmap.png";
	} else {
		$url = $link;
	}
	print "File name: ".$name."\n";
	tie my %h_images , 'IO::Dir', $imagedir;
	if (!(defined($h_images{$name}))) {
		print "Need to download: ".$url." to ".$imagedir."/".$name." \n";
		system("wget \"$url\" -O \"$imagedir/$name\" 2> /dev/null");
	}
	return "<imagedata fileref='". $imagedir."/".$name."'/>";

}

sub replace () {
	open(FILE, "< $file") or die "Can't open $file perhaps not in the correct dir? Error: $!";
	undef $/;
	my $local = <FILE>;
	close(FILE);
	# look for images...
	if ( $local =~ "m#<imagedata fileref='/".$path."/\\w+\?action=AttachFile&amp;do=get&amp;target=([^']+)'/>#" ) {
		# ..and replace the paths
		$local =~ s#<imagedata fileref='([^'"<>]+)'/>#create($1)#eg;
		open(FILE, "> $file") or die "Can't open $file for writing";
		print FILE $local;
		close(FILE);
	} else {
		print "File $file has already been modified.\n";
	}
	
}

&replace();



