#!/usr/bin/perl -w
# -*- mode: cperl; coding: utf-8 -*-
# Copyright © 2005-2010 Jonas Smedegaard <dr@jones.dk>
# Description: Reformat licencecheck output to DEP5 copyright format
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2, or (at
# your option) any later version.
#
# 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.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

print "Format-Specification: http://svn.debian.org/wsvn/dep/web/deps/dep5.mdwn?rev=135\n";
print "X-Draft: Autogenerated by CDBS snippet copyright-check.mk\n\n";
$n=0; while (<>) {
	if (/^([^:\s][^:]+):[\s]+(\S.*?)\s*$/) {
		$files[$n]{name}=$1;
		$files[$n]{license}=$2;
	};
	if (/^\s*\[Copyright:\s*(\S.*?)\s*\]/) {
		$files[$n]{copyright}=$1;
	};
	/^$/ and $n++;
};
foreach $file (@files) {
	$file->{license} =~ s/\s*\(unversioned\/unknown version\)//;
	$file->{license} =~ s/\s*\(with incorrect FSF address\)//;
	$file->{license} =~ s/\s+\(v([^)]+) or later\)/-$1+/;
	$file->{license} =~ s/\s+\(v([^)]+)\)/-$1/;
	$file->{license} =~ s/\s*(\*No copyright\*)\s*// and $file->{copyright} = $1;
	$file->{license} =~ s/^\s*(GENERATED FILE)/UNKNOWN/;
	$file->{license} =~ s/\s+(GENERATED FILE)//;
	$file->{copyright} =~ s/^&copy;\s*//;
	$file->{copyright} =~ s/(?<=(\b\d{4}))(?{$y=$^N})\s*[,-]\s*((??{$y+1}))\b/-$2/g;
	$file->{copyright} =~ s/(?<=\b\d{4})\s*-\s*\d{4}(?=\s*-\s*(\d{4})\b)//g;
	$file->{copyright} =~ s/\b(\d{4}),?\s+([\S^\d])/$1, $2/g;
	my @ownerlines = grep {/\w\w/} split /\s\/\s/, $file->{copyright};
	my @ownerlines_clean = ();
	my %owneryears = ();
	for $ownerline ( @ownerlines ) {
		my ($owneryear, $owner) = $ownerline =~ /^([\d\-,\s]*)\s*+(.*)/;
		$owner =~ s/^by\s+//;
		$owner =~ s/,?\s+All Rights Reserved\.?//gi;
		push @ownerlines_clean, "$owneryear$owner";
		push @{ $owneryears{"$owner"} }, $owneryear;
	};
	my @owners = sort keys %owneryears;
	my $pattern = join ("\n", $file->{license}, @owners);
	push @{ $patternfiles{"$pattern"} }, $file->{name};
	push @{ $patternownerlines{"$pattern"} }, @ownerlines_clean;
	$patternlicense{"$pattern"} = $file->{license};
};
foreach $pattern ( sort {
			@{$patternfiles{$b}} <=> @{$patternfiles{$a}}
			||
			$a cmp $b
		} keys %patternfiles ) {
	my $prev;
	@ownerlines_unique = grep((!defined $prev || $_ ne $prev) && (($prev) = $_), sort @{ $patternownerlines{$pattern} });
	print "Files: ", join(",\n\t", sort @{ $patternfiles{$pattern} }), "\n";
	print "Copyright: ", join("\n\t", @ownerlines_unique), "\n";
	print "License: $patternlicense{$pattern}\n FIXME\n\n";
};
