#!/usr/bin/perl

use strict;
use warnings;
use 5.010;
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("*.xml") ) {
    my $xml = XMLin(
        $file,
        KeyAttr => { translator => "+name", contributor => "+name" },
        ForceArray => [ "translator", "contributor" ]
    );

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

    my $copyright;
    foreach my $translator ( sort keys %{$translators} ) {
        $copyright .= " $year,";
        $copyright .= ' ' . $translators->{$translator}->{name};
        $copyright .= " <" . $translators->{$translator}->{email} . ">"
            if $translators->{$translator}->{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';
say $outfh $template;
close $outfh;
