#!/usr/bin/env perl
#
# Anope IRC Services <https://www.anope.org/>
#
# Copyright (C) 2003-2026 Anope Contributors
#
# Anope is free software. You can use, modify, and/or distribute it under the
# terms of version 2 of the GNU General Public License. See docs/LICENSE.txt
# for the complete terms of this license and docs/AUTHORS.txt for a list of
# contributors.
#
# Based on the original code of Epona by Lara
# Based on the original code of Services by Andy Church
#
# SPDX-License-Identifier: GPL-2.0-only

use v5.26.0;
use strict;
use warnings FATAL => qw(all);

use File::Basename        qw(dirname);
use File::Spec::Functions qw(catfile);
use FindBin               qw($RealDir);
use Digest::SHA           qw(sha256_hex);

my @ignored_committers = (
	'2f51f982f0630009bad5e02e49212112d1f25785e6ce76847a48774b42dce7e4' # requested via email
);

my %committers;
for my $committer (split /\n+/, `git log --pretty='%an <%ae>%n%(trailers:key=Co-Authored-By,valueonly)' HEAD`) {
	$committers{$committer} ||= 0;
	$committers{$committer} += 1;
}

my %authors;
for my $committer (keys %committers) {
	open(my $fh, '-|', 'git', 'check-mailmap', $committer);
	chomp(my $author = <$fh>);
	close $fh;

	next unless $author =~ /^(.+) <(.+)>$/;
	my ($author_name, $author_email) = ($1, $2);

	# Skip bots and other non-human committers.
	next if $author_name =~ /\[bot\]$/;
	next if $author_name =~ /^\(svnadmin\)$/;

	# Skip ignored committers.
	next if grep { $_ eq sha256_hex($author_email) } @ignored_committers;

	# Omit uncontactable email addresses.
	$author = $author_name if $author_email =~ /^(?:\S+\@localhost|\S+\@users.noreply.github.com)$/;

	$authors{$author} ||= 0;
	$authors{$author} += $committers{$committer};
}


my $author_file = catfile dirname(dirname($RealDir)), 'docs', 'AUTHORS.txt';
open(my $fh, '>', $author_file) or die "Unable to write $author_file: $!";
say $fh <<"EOH";
Since the first commit in March 2004 ${\scalar %authors} people have submitted patches, commits,
and other useful contributions to Anope. These people, ordered by the number of
contributions they have made, are:
EOH

for my $author (sort { $authors{$b} <=> $authors{$a} or lc($a) cmp lc($b) } keys %authors) {
	say $fh "  * $author";
}
close $fh;

if ($ENV{MKAUTHORS_COMMIT} // 1) {
	system 'git', 'commit',
		'--message', 'Update author list.',
		'--', $author_file;
}
