use Cwd;
use feature ":5.10";
my $cwd = getcwd;

require "$ENV{srcdir}/doc/mk.util.pm";

$ENV{TEXINPUTS}  = "$ENV{mudir}/tex";
$ENV{OSFONTDIR}  = "$ENV{mudir}/fonts";
$ENV{TEXMFCACHE} = "$cwd/tex-cache";

my %meta;
my @srcs;
my $title;

for ( @ARGV )
{
    if ( m,^(.*)=(.*)$, )
    {
        $meta{$1} = $2;
    }
    else
    {
        push @srcs, $_;
    }
}

print STDERR %meta, "\n";
print STDERR @srcs, "\n";

my $cmd = "$ENV{mu} --html | $ENV{svgtex} -s 1.2 > $util::out";
my $main = $srcs[0];
open OUT, "| $cmd" or die "error opening pipeline";
open SRC, $main;

while ( <SRC> )
{
    if ( m,^# (.*), )
    {
        $title = $1;
        last;
    }
}

given ( $main =~ s,.*/,,r )
{
    when ( m,^blog\.index, )  { $meta{title} = "divine blog" }
    when ( m,^blog\., )       { $meta{title} = "divine blog: $title" }
    when ( m,^man\.index, )   { $meta{title} = "divine manual" }
    when ( m,^man\., )        { $meta{title} = "divine manual: $title" }
    when ( m,^web\.(.*?)\., ) { $meta{title} = "divine: $1" }
    default                   { $meta{title} = "divine" }
}

for my $f ( "$ENV{srcdir}/doc/tmpl.head.txt", @srcs, "$ENV{srcdir}/doc/tmpl.foot.txt" )
{
    my $fh = util::open( $f );

    while ( <$fh> )
    {
        print OUT s,\@([a-z_]+)\@,$meta{$1},gr;
    }
}

close OUT or die "error running $cmd";
