#!/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];
our @langs = ('de','es','fr');


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;
	# 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;
		$url =~ s/&amp;/\&/g;
	}
	print "File name: ".$name."\n";
	tie my %h_images , 'IO::Dir', $imagedir;
	if ($name eq 'worldmap.png' or !(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");
	}
	if ($name eq 'worldmap.png'){
		foreach (@langs) {
			$url = "http://www.skolelinux.no/slschools/worldmap.php?lang=$_&amp;image=worldmap.png";
			print "Need to download: ".$url." to ".$imagedir."/".$_."/".$name." \n";
			print "Name: ".$name."\n";
			system("wget \"$url\" -O \"$imagedir/$_/$name\" 2> /dev/null");
		}
	}
	# Sloppy workaround to reduce smiley sizes in PDF, doesn't play nice with xsltproc.
	my $scale = '';
#	if ($name =~ m/^(smile|alert|sad).png$/){
#		$scale = "scale='50'";
#	}
	return "<imagedata $scale 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();



