#!/usr/bin/perl
# Author:       2012 David Prévot <taffit@debian.org>
# License:      GPLv2 or later
#
# This small script fetch the CopyRight page from the wiki
# and makes it copyright-format (aka DEP5) compliant.

# The extra third argument, [<type>], prepares the copyright
# in DocBook format if type is dbk.

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

my $base = 'https://wiki.debian.org';
my $path = $ARGV[0];
my $cdir = $ARGV[1];
my $type = '';
$type = $ARGV[2] if defined $ARGV[2];
my $file = 'copyright.manual';
$file = 'copyright.xml' if $type eq 'dbk';
my $name = 'CopyRight';
my %langs = (
	'Brazilian Portuguese'=> 'pt_BR',
	'Bokmål'	=> 'nb',
	'Simplified Chinese' => 'zh',
	'Traditional Chinese' => 'zh_Hant',
	'Czech'		=> 'cs',
	'Danish'	=> 'da',
	'Dutch'		=> 'nl',
	'French'	=> 'fr',
	'German'	=> 'de',
	'Italian'	=> 'it',
	'Japanese'	=> 'ja',
	'Norwegian Bokmål' => 'nb',
	'Polish'	=> 'pl',
	'Portuguese'	=> 'pt_PT',
	'Romanian'	=> 'ro',
	'Spanish'	=> 'es',
	'Swedish'	=> 'sv',
	'Ukrainian'	=> 'uk',
);

sub copyright ($) {
	# get the list of copyright holders with years
	my $list = shift;
	$list =~ s/ and /, /;
	my @holders = split(/\), /,$list);
	my $result = '';
	foreach my $holder (@holders) {
		# separate year ($1) from holder name
		$holder =~ s/ \((\d.*?)\)?$//;
		if ($type eq 'dbk') {
			$result .= "<copyright>\n";
			my @dates = split(/, /,$1);
			foreach my $date (@dates) {
				$result .= "  <year>$date</year>\n";
			}
			$result .= "  <holder>$holder</holder>\n";
			$result .= "</copyright>\n";

		} else {
			$result .= "  $1 $holder\n";
		}
	}
	$result =~ s/^ //;
	return $result;
}

my $url = "$base/$path/$name";
print "Fetching $url\n";
system("wget -q '$url' -O - | sed \"s/<p/\\n<p/g\" > '$file'");

my $buffer;
open(FILE, "< $file") or die "Can't open $file perhaps not in the correct dir? Error: $!";
while(<FILE>){
	my $short = $cdir;
	$short =~ s/-manual//;
	if ($_ =~ m/This document is written and copyrighted by (.*?) and is released under the GPL(\d+) or any later version\./){
	    if ($type eq 'dbk') {
		$buffer = "<!-- START en -->\n";
		$buffer .= copyright($1);
		$buffer .= "<!-- END en -->\n";
	    } else {
		$buffer = "Files: documentation/$short/$cdir.xml documentation/$short/$cdir-stripped.xml documentation/$short/source/AllInOne-$cdir.xml documentation/$short/$cdir.pot\n";
		$buffer .= "Copyright:".copyright($1);
		$buffer .= "License: GPL-$2+\n\n";
	    }
	}
}
close(FILE);

open(FILE, "> $file") or die "Can't open $file for writing";
print FILE $buffer;
close(FILE);
