#!/usr/bin/env perl

# Copyright 2016-2017 SUSE LLC
# SPDX-License-Identifier: GPL-2.0-or-later

# Internal script for generate-documentation to create markdown from POD
# in os-autoinst

use strict;
use warnings;

my $parser;

eval 'use Pod::Markdown';
eval {
    # make sure compile-all does not barf here
    $parser = Pod::Markdown->new();
};

if ($@ || !$parser) {
    print "Make sure to install Pod::Markdown if you meant to run this script\n";
    die $@;
}

my $data_dir = './src/';
opendir my $dh, $data_dir or die "Cannot read directories: $data_dir";
my @files = grep { /\.pm$/ } readdir $dh;

foreach my $current_file (@files) {

    open my $ifh, '<', $data_dir . $current_file or die "Cannot open $current_file";
    $current_file =~ s/^(.*)\.pm$/$1.md/;
    open my $ofh, '>', $current_file or die "Cannot open $current_file";

    print "Transforming $current_file\n";
    # We don't have a direct equivalent of include::header in Pod::Markdown
    # but we can just write it out if it exists
    if (-e 'header.md') {
        open my $hfh, '<', 'header.md';
        print {$ofh} <$hfh>;
        print $ofh "\n";
        close $hfh;
    }
    $parser->parse_from_filehandle($ifh);

    print $ofh $parser->as_markdown();
    close $ofh;
    close $ifh;

}
