#! /usr/bin/perl
use warnings;
use strict;
use integer;

our $pat_mnstd  = qr/^.. .{1,12}$/;
our $Maintainer = 'Maintainer';

# This helper script checks for different maintainers who claim the same
# e-mail address.  Because such different maintainers are probably
# really the same maintainer, the script warns the developer to look
# into the matter.  Additionally, the script ensures that the std maint
# names fit the proper format.  (It does not check alphebetization,
# though.  See `sort-maint' for this.)
#
# usage: check-maint maint.txt Packages
#
#

my %mnlong; # long-form maintainer names
my %mnstd ; # debram-standard short-form maintainer names
my %addr  ; # e-mail addresses

@ARGV == 2 or die "usage: $0 maint.txt Packages\n";
my ( $maint_txt, $packages_file ) = @ARGV;

# Read maint.txt.
{
    local $/ = '';
    open MAINT_TXT, '<', $maint_txt
        or die "$0: cannot open maint file $maint_txt\n";
    while ( <MAINT_TXT> ) {
        my @c = grep { /\S/ } split '\n';
        my $mnstd = shift @c;
        $mnstd =~ $pat_mnstd or die "$0: bad std maint name $mnstd\n";
        $mnstd{$mnstd}
            and die "$0: std maint name $mnstd given twice\n";
        for ( @c ) {
            defined $mnlong{$_}
                and die "$0: long maint name $_ given twice\n";
            $mnlong{$_} = $mnstd;
        }
        $mnstd{$mnstd} = { mnlong => [ sort @c ], addr => {} };
    }
    close MAINT_TXT;
}

# Read the e-mail addresses from the Packages file.
{
    open PACKAGES_FILE, '<', $packages_file
        or die "$0: cannot open Packages file $packages_file\n";
    while ( <PACKAGES_FILE> ) {
        my( $mnlong, $addr ) =
            /^$Maintainer:[ \t]+([^<>]+?)[ \t]+<([^<>]+?)>/o
            or next;
        my $mnstd = $mnlong{$mnlong};
        defined $mnstd or print(
            "unknown $Maintainer $mnlong <$addr>\n\n"
        ), next;
        $mnstd{$mnstd}{addr}{$addr} = 1;
        $addr{$addr}{$mnstd}        = 1;
    }
    close PACKAGES_FILE;
}

# Report e-mail addresses claimed by multiple maintainers.
my $exit = 0;
for my $addr ( keys %addr ) {
    if ( scalar keys %{ $addr{$addr} } > 1 ) {
        print "$_ <$addr>\n" for keys %{ $addr{$addr} };
        print "\n";
    }
}

