#!/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 = "https://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;
	# more permissive regex for smiley and alike
	$name =~ s#$base/.*/([\w\d]+)#$1#g;
	$url = $link;
	$url =~ s/&amp;/\&/g;
	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";
		print "Name: ".$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( width='\\d+')\? fileref=\"/".$path."/\\w+\?action=AttachFile&amp;do=get&amp;target=([^']+)\"( width=\"\\d+\")\?/>#"
			or $local =~ "m#<imagedata( depth=\"\\d+\")\? fileref=\"([^\"]+)\"( width=\"\\d+\")\?/>#") {
		# ..and replace the paths
		$local =~ s#<imagedata( depth="\d+")? fileref="([^'"<>]+)"( width="\d+")?/>#create($2)#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();



