#!/usr/bin/perl -w
#
# This file is used to redirect bweb to the exact file of the documentation
#
use strict;
use Data::Dumper;
use CGI;

# Creation mode, put the directory to scan in argument
if (scalar(@ARGV) > 0) {
    my %index;
    my $dir = $ARGV[0];
    # Index this directory
    open(FP, ">.idx") or die "ERROR: unable to open index file";

    chdir($dir) or die "ERROR: Unable to chdir to $dir";

    foreach my $l (`grep '<A NAME="' *.html`) {

        # Monitor_Configuration.html:<A NAME="MonitorResource"></A>
        if ($l =~ m/^([^:]+):<A NAME="(.+?)">/) {
            my ($key, $file) = ($2, $1);
            if ($key !~ /^(tex2html|\d)/) {
                $index{$key} = $file;
            }
        }
    }

    print FP Data::Dumper::Dumper(\%index);
    close(FP);
    exit;
}

################################################################

my $base = "http://www.baculasystems.com/docs";
if (!CGI::param()) {
    print CGI::redirect($base);
    exit 0;
}

my $version = CGI:param('version') || '6.0';
if ($version !~ /^(\d+\.\d+)$/) {
    print CGI::redirect($base);
    exit 0;
}

$base = "$base/docs/${version}.x-manuals/en/";

# Key arg is mandatory
my $key = CGI::param('key');
if ($key !~ /^([\w\d:\.\-]{1,127})$/) {
    print CGI::redirect($base);
}
$key = $1;

my $manual = CGI::param('manual') || "main"; 
if ($manual !~ /^(main|console|operator)$/) {
    print CGI::redirect("$base/main/main");
}
$manual = $1;

if (!open(FP, ".idx")) {
    print CGI::redirect($base);
    exit 0;
}

my $f=''; my $tmpbuffer;
while(read FP,$tmpbuffer,4096)
{
    $f .= $tmpbuffer;
}
close(FP);

our $VAR1;

no strict; # I have no idea of the contents of the file
eval "$f" ;
use strict;

if (exists $VAR1->{$key}) {
    print CGI::redirect("$base/$manual/$manual" . $VAR1->{$key} . '#' . $key);
    exit 0;
}

print CGI::redirect($base);
