#!/usr/bin/env perl
# Author: Karl Wette, 2023

use strict;

my $package = "@PACKAGE@";
my $packagename = "@PACKAGE_NAME@";
my $markdown2html = "@MARKDOWN2HTML@";
my $srcdir = "@srcdir@";

sub markdown_to_html {
  my ($file) = @_;
  die "$0: $file does not exist" unless -f $file;
  my $doxyblock = ($markdown2html eq "cat") ? "verbatim" : "htmlonly";
  print "\\${doxyblock}\n";
  system("$markdown2html $file") == 0 or die "$0: $markdown2html $file failed";
  print "\\end${doxyblock}\n";
}

print <<EOF;
/* Generated by make_autogen_dox */
EOF

# generate main page
print <<EOF;

/** \\mainpage

EOF
markdown_to_html("in/README.md");
print <<EOF;
\\htmlonly
<h2>License</h2>
\\endhtmlonly
\\verbinclude COPYING
*/
EOF

## generate contributing page
if (-f "in/CONTRIBUTING.md") {
  print <<EOF;

/** \\page ${package}_contributing Contributing Guide

EOF
  markdown_to_html("in/CONTRIBUTING.md");
  print <<EOF;

*/
EOF
}

## generate authors page
my %maintainer_names;
my @lalsuite_maintainers;
my @package_maintainers;
my @authors;
open CODEOWNERS, "${srcdir}/gitlab-CODEOWNERS" or die "$0: could not open ${srcdir}/gitlab-CODEOWNERS: $!";
while (<CODEOWNERS>) {
  chomp;
  next unless /./;
  if (/^#/) {
    if (/^#\s*@/) {
      if (/^#\s*(@\S+)\s*=\s*(.*?)\s*$/) {
        $maintainer_names{$1} = $2;
      } else {
        die "$0: cannot parse gitlab-CODEOWNERS line '$_'\n";
      }
    }
  } else {
    my @tokens = split /\s+/, $_;
    my $path = shift @tokens;
    if ($path =~ m|^${package}/|) {
      foreach my $name (@tokens) {
        if (grep({ $_ eq $name } @package_maintainers) == 0) {
          push @package_maintainers, $name;
        }
      }
    } elsif ($path !~ m|^lal|) {
      foreach my $name (@tokens) {
        if (grep({ $_ eq $name } @lalsuite_maintainers) == 0) {
          push @lalsuite_maintainers, $name;
        }
      }
    }
  }
}
close CODEOWNERS;
open AUTHORS, "in/AUTHORS" or die "$0: could not open in/AUTHORS: $!";
while (<AUTHORS>) {
  chomp;
  push @authors, $_;
}
close AUTHORS;
sub no_break_author_names { $_ = $_[0]; s/\s+/&nbsp;/g; s/-/&#8209;/g; $_ }
my $lalsuite_maintainer_list = join(" &ensp; ", map({ no_break_author_names($maintainer_names{$_}) } @lalsuite_maintainers));
my $package_maintainer_list = join(" &ensp; ", map({ no_break_author_names($maintainer_names{$_}) } @package_maintainers));
my $author_list = join(" &ensp; ", map({ no_break_author_names($_) } @authors));
print <<EOF;

/** \\page ${package}_authors Authors/Maintainers
\\htmlonly
<h2>Authors</h2>
<p>$author_list</p>
EOF
if (@package_maintainers > 0) {
  print <<EOF;
<h2>$packagename Maintainers</h2>
<p>$package_maintainer_list</p>
EOF
}
print <<EOF;
<h2>LALSuite Maintainers</h2>
<p>$lalsuite_maintainer_list</p>
\\endhtmlonly
*/
EOF
