#!/usr/bin/env perl
#
# InspIRCd -- Internet Relay Chat Daemon
#
#   Copyright (C) 2020-2021 Sadie Powell <sadie@witchery.services>
#
# This file is part of InspIRCd.  InspIRCd is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#


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

use CommonMark              ();
use File::Basename          qw(basename dirname);
use File::Spec::Functions   qw(catdir catfile rel2abs);
use FindBin                 qw($RealDir);
use HTML::FormatText        ();
use HTML::TreeBuilder       ();
use Text::Sentence          qw(split_sentences);
use YAML                    qw(LoadFile);

use lib dirname $RealDir;
use make::common;
use make::console;

unless (scalar @ARGV) {
	say STDERR console_format "<|GREEN Usage:|> $0 <<|UNDERLINE DOCS-SITE|>>";
	exit 1;
}

my %version = get_version();
my $docdir = rel2abs catdir $ARGV[0], 'docs', $version{MAJOR}, 'modules';
print_error "unable to find the module directory at $docdir!" unless -d $docdir;

my $root = dirname $RealDir;
for my $module (<$root/src/modules/extra/m_*.cpp>, <$root/src/modules/m_*.cpp>, <$root/src/modules/m_*/main.cpp>) {
	print_error "unable to extract module name from $module!" unless $module =~ /m_(\w+)[.\/]/;
	my $docfile = catfile $docdir, "$1.yml";
	print_error "unable to find the module documentation at $docfile!" unless -f $docfile;

	my ($docdata, undef, undef) = LoadFile($docfile) or print_error "unable to read from $docfile: $!";
	print_error "unable to find the module description in $docfile!" unless $docdata->{description};

	my $docraw = $docdata->{description} =~ s/^(?:This module )//r;
	my $docrendered = CommonMark->markdown_to_html(ucfirst $docraw);
	my $docplain = HTML::FormatText->new(leftmargin => 0, rightmargin => ~0)->format(HTML::TreeBuilder->new->parse($docrendered));

	my $description = (split_sentences $docplain)[0] =~ s/"/\\"/gr;
	chomp($description);

	open(my $mih, $module) or print_error "unable to read from $module: $!";
	my @lines;
	for my $line (<$mih>) {
		chomp $line;
		if ($line =~ /(\t+return Version\(")[^"]+(",.+)/) {
			push @lines, join '', $1, $description, $2;
		} else {
			push @lines, $line;
		}
	}
	close $mih;

	open(my $moh, '>', $module) or print_error "unable to write to $module: $!";
	for my $line (@lines) {
		say $moh $line;
	}
	close $moh;
}
