#!/usr/bin/perl

use strict;
use warnings;
use XML::Simple;
use utf8::all;
use autodie;

open my $infh, '<', 'debian/copyright.in';
my $template;
{
    local $/ = undef;
    $template = <$infh>;
}
close $infh;

my $list;
foreach my $file ( glob("*.csl") ) {
    my $csl = XMLin(
        $file,
        KeyAttr => { author => "+name", contributor => "+name" },
        ForceArray => [ "author", "contributor" ]
    );

    my $authors      = $csl->{info}->{author};
    my $contributors = $csl->{info}->{contributor}
        unless $authors;    # only if we have no author(s)
    my $updated      = $csl->{info}->{updated};
    my $year         = $1 if $updated =~ m/^(\d{4}).+/;

    my $copyright;
    foreach my $author ( sort keys %{$authors} ) {
        $copyright .= " $year,";
        $copyright .= ' ' . $authors->{$author}->{name};
        $copyright .= " <" . $authors->{$author}->{email} . ">"
            if $authors->{$author}->{email};
        $copyright .= "\n";
    }

    foreach my $contributor ( sort keys %{$contributors} ) {
        $copyright .= " $year,";
        $copyright .= ' ' . $contributors->{$contributor}->{name};
        $copyright .= " <" . $contributors->{$contributor}->{email} . ">"
            if $contributors->{$contributor}->{email};
        $copyright .= "\n";
    }

    if ($copyright) {
        $list
            .= "Files: $file\n"
            . "Copyright:$copyright"
            . "License: CC-BY-SA-3.0\n\n";
    }
}

$template =~ s/#LIST#\n\n/$list/;

open my $outfh, '>', 'debian/copyright';
print $outfh $template;
close $outfh;
