#! /usr/bin/perl -w
use strict;

# Build a copyright file based on the files in debian/copyrights.

use Text::Wrap qw(wrap);

if (@ARGV < 2) {
    print STDERR "Usage: $0 <free/non-free> <header>\n";
    exit 1;
}

my $status = shift;
my $header = shift;

my (%documents, %copyrights);

opendir COPYRIGHTS, "debian/copyrights/$status"
    or die "Can't open debian/copyrights/$status directory: $!";
for my $copy (readdir COPYRIGHTS) {
    next unless -f "debian/copyrights/$status/$copy";
    open COPYRIGHT, "< debian/copyrights/$status/$copy"
	or die "Can't open debian/copyrights/$status/$copy: $!";
    while (<COPYRIGHT>) {
	chomp;
	last if /^$/;
	next unless s/^(?:mini-)?HOWTO: //o;
	push @{$documents{$copy}}, $_;
    }
    $copyrights{$copy} = join '', <COPYRIGHT>;
    close COPYRIGHT;
}
closedir COPYRIGHTS;

system "cat \Q$header\E";

$Text::Wrap::columns = 76;

for my $copy (sort keys %documents) {
    print "\n", '=' x 76, "\n\n";
    my @documents = sort @{$documents{$copy}};
    print "The following licence covers these documents:\n";
    print wrap('  ', '  ', (join ', ', @documents) . "\n");
    print "\n";
    print $copyrights{$copy};
}
