#!/usr/bin/perl

# Adds version links to doc pages, assumption:
#
#   /project/doc      <- latest version
#   /project/doc/$x   <- older versions, $x must start with a digit and '_' is replaced with a '.' for display.
#
use v5.36;

my $VER = qr{[0-9][^/]*};
my $cur = shift;
my $base = $cur =~ s{/$VER$}{}r;
my %pages = map +($_ =~ s{^pub/}{}r =~ s{\.html$}{}r,1), @ARGV;
my $links = '';

sub num($s) { $s =~ s/([0-9]+)/sprintf '%05d', $1/erg }

my @ver =
    sort { num($b) cmp num($a) }
    grep m{^(.+)/($VER)$} && $1 eq $base, keys %pages;

sub lnk($ver) {
    my $v = $ver eq $base ? 'latest' : $ver =~ s{^.+/($VER)$}{$1}r =~ s/_/./rg;
    $cur eq $ver ? "**$v**" : "[$v](/$ver)";
}

$links = 'Version: '.join(' / ', map lnk($_), $base, @ver)."\n\n" if @ver;

my $firstsec = 1;
while(<STDIN>) {
    if ($firstsec && /^#/) {
        $firstsec = 0;
        print $links;
    }
    print;
};
