#!/usr/bin/perl -w
# -*- mode: CPerl; tab-width: 8; fill-column: 70; -*-

use lib qw( /usr/share/docs-build/docinfo2html );
#use lib qw( ../data/docinfo2html );
use Heap::docinfo;
use HTML::Element;

$moduleid=$ARGV[0];
$docinfo_file=$ARGV[1];
$outfile=$ARGV[2];
$docinfo = {};

die unless $moduleid eq "" or -f $docinfo_file or $outfile eq "";

# transform $moduleid to match RPM package name
$moduleid =~ s/\.([^.]+)$/-$1/;

$bugzilla_search_url="https://bugzilla.altlinux.org/buglist.cgi?component=docs-$moduleid&component_type=equals&bug_status=UNCONFIRMED&bug_status=NEW&bug_status=ASSIGNED&bug_status=REOPENED";
$bugzilla_add_url="https://bugzilla.altlinux.org/enter_bug.cgi?product=ALT%20Linux%20Sisyphus";

open my $fh, $docinfo_file || die $!;
while (<$fh>) {
  /^([^:]+):\s+(.*)$/;
  if (exists $docinfo->{lc($1)}) {
    $docinfo->{lc($1)} .= $Heap::docinfo::separator."$2";
    next
  }
  $docinfo->{lc($1)} = "$2";
}
close $fh;

my $table = HTML::Element->new('table', 'border' => '"1"');
foreach (@{Heap::docinfo::order}) {
  my $k = lc;
  my $tk = $_;
  next if ! exists $docinfo->{$k} or $docinfo->{$k} eq "";
  $tk = $Heap::docinfo::translate->{$k} if $Heap::docinfo::translate->{$k};

  if ($k eq "license") {
    my $a = HTML::Element->new('a', 'href' => "License");
    $a->push_content($docinfo->{$k});
    $docinfo->{$k} = $a;
  }
  if ($k eq "url") {
    my $a = HTML::Element->new('a', 'href' => $docinfo->{$k});
    $a->push_content($docinfo->{$k});
    $docinfo->{$k} = $a;
  }
  $table->push_content( ['tr', ['th', $tk], ['td', $docinfo->{$k}]] );
}

my $a1 = HTML::Element->new('a', 'href' => $bugzilla_search_url);
$a1->push_content("   ");
$table->push_content( ['tr', ['th', '&nbsp;'], ['td', $a1 ]] );

my $a2 = HTML::Element->new('a', 'href' => $bugzilla_add_url);
$a2->push_content("  ");
$table->push_content( ['tr', ['th', '&nbsp;'], ['td', $a2, " (  docs-$moduleid)"]] );

my $h1 = HTML::Element->new('h1');
$h1->push_content(" :");

#<meta http-equiv="Content-Type" content="text/html; charset=Windows-1251" />
my $html = HTML::Element->new('html');
my $meta = HTML::Element->new('meta', 'http-equiv' => 'Content-Type', 'content' => "text/html; charset=koi8-r");
$html->push_content(['head', $meta, ['title', $docinfo->{title}]], ['body', $h1, $table ] );

close STDOUT;
open STDOUT, ">$outfile" || die $!;
print $html->as_HTML('<>','   ',{});
close STDOUT;
