#!/usr/bin/perl

use v5.36;

my $man = $ARGV[0] eq 'man';
my $mdoc = $ARGV[0] eq 'mdoc';
my $pod = $ARGV[0] eq 'pod';

sub man2url($page) {
    +{qw{
        globsterctl(1)      /globster/ctl
        globster-launch(1)  /globster/launch
        globster(1)         /globster/daemon
        globster-api(7)     /globster/api
        ncdu(1)             /ncdu/man
    }}->{$page||''} || ($page =~ /(.+)\((.)\)/ and "https://manned.org/man/$1.$2");
}

sub pod2url($page, $sect='') {
    my $lnk = {
        'TUWF'           => '/tuwf/man',
        'TUWF::DB'       => '/tuwf/man/db',
        'TUWF::Intro'    => '/tuwf/man/intro',
        'TUWF::Misc'     => '/tuwf/man/misc',
        'TUWF::Request'  => '/tuwf/man/request',
        'TUWF::Response' => '/tuwf/man/response',
        'TUWF::XML'      => '/tuwf/man/xml',
        'TUWF::Validate' => '/tuwf/man/validate',
        ''               => '',
    }->{$page||''} // "https://metacpan.org/pod/$page";
    $lnk .= '#'.(lc $sect =~ s/\s+/-/gsr) if $sect;
    $lnk
}

my $data = '';
my $insyn = 0;
while (<STDIN>) {
    # Improve styling of mdoc synopsis
    $insyn = /^# SYNOPSIS$/ if /^#/;
    if ($mdoc && $insyn) {
        s/\\\[`/<span class="synopt">[`/g;
        s/\\]/]<\/span>/g;
    }

    s/^  // if $pod && /^      /; # POD code sections have too much indentation

    $data .= $_;
}


$_ = $data;

# Turn man page references into links
s{\[([^\]]+)\]\{\.Xr\}}{sprintf '[%s](%s)', $1, man2url $1}eg if $mdoc;
s{\[([^\]]+)\]\(\)\{manual="([^"]+\))"\}}{sprintf '[%s](%s)', $1, man2url $2}seg if $pod;
s{\*\*([a-zA-Z0-9-]+)\*\*\(([1-8])\)}{sprintf '[%s](%s)', "$1($2)", man2url "$1($2)"}eg if $man;

# POD references too
s{\[([^\]]+)\]\(\)\{manual="([^"\)]+)"\}}{sprintf '[%s](%s)', $1, pod2url $2}seg if $pod;
s{\[([^\]]+)\]\(\)\{manual="([^"\)]+)"\s+section="([^"]+)"\}}{sprintf '[%s](%s)', $1, pod2url $2, $3}seg if $pod;

print;
