#!/perl -w
# NAME: fggenmenu.pl
# AIM: VERY SPECIFIC - Take the internal menu javascript, and convert to HTML
# 2010/04/12 - some little fixes...
# 2010/03/24 - geoff mclane - http://geoffair.net/mperl/
use strict;
use warnings;
use File::Basename;
use Cwd;
unshift(@INC, 'C:\GTools\perl');
require 'logfile.pl' or die "Unable to load logfile.pl ...\n";
# log file stuff
my ($LF);
my $pgmname = $0;
if ($pgmname =~ /\w{1}:\\.*/) {
    my @tmpsp = split(/\\/,$pgmname);
    $pgmname = $tmpsp[-1];
}
my $perl_dir = 'C:\GTools\perl';
my $outfile = $perl_dir."\\temp.$pgmname.txt";
open_log($outfile);

# user variables
my $load_log = 1;

my $in_file = 'C:\HOMEPAGE\FG\js\template2.js';
my $out_file = $perl_dir."\\tempmenu.htm";
my $parent = "";
#my $parent = "../../";
my $gen_javascript = 0;
my $include_all_sections = 1;

### program variables
my @warnings = ();
my $cwd = cwd();

sub show_warnings();

sub pgm_exit($$) {
    my ($val,$msg) = @_;
    if (length($msg)) {
        $msg .= "\n" if (!($msg =~ /\n$/));
        prt($msg);
    }
    show_warnings();
    close_log($outfile,$load_log);
    exit($val);
}


sub prtw($) {
   my ($tx) = shift;
   $tx =~ s/\n$//;
   prt("$tx\n");
   push(@warnings,$tx);
}

sub show_warnings() {
   if (@warnings) {
      prt( "\nGot ".scalar @warnings." WARNINGS...\n" );
      foreach my $itm (@warnings) {
         prt("$itm\n");
      }
      prt("\n");
   } else {
      prt( "No warnings issued.\n\n" );
   }
}

sub gm_strip_quotes {
	my ($ln) = shift;
	$ln = substr($ln,1,length($ln)-2) if ($ln =~ /^".*"$/);
	return $ln;
}

sub gm_strip_both_quotes {
	my ($ln) = shift;
    $ln = gm_strip_quotes($ln);
	$ln = substr($ln,1,length($ln)-2) if ($ln =~ /^'.*'$/);
	return $ln;
}

sub ignored_lines($) {
    my ($ln) = shift;
    return 1 if ($ln =~ /^\s*\{\s*$/);
    return 1 if ($ln =~ /^\s*var\s+path\s+/); # = arguments[0];
    return 1 if ($ln =~ /^\s*var\s+offset\s+/); # = arguments[1];
    return 1 if ($ln =~ /^\s*var\s+\$dir\s+/); # = location.href.substring(0, location.href.lastIndexOf('/')+1);]
    return 1 if ($ln =~ /^\s*var\s+\$fnm\s+/); # = location.href.substring($dir.length,location.href.length+1);]
    return 1 if ($ln =~ /^\s*if\s+\(\$fnm\s+/); # == '') $fnm = 'index.html';]
    return 1 if ($ln =~ /^\s*var\s+regex\s+/);  # = /http/;]
    return 1 if ($ln =~ /^\s*var\s+ma\s+/);  # = new Array(]
    return 0;
}

sub split_comma($) {
    my ($ln) = @_;
    my $len = length($ln);
    my ($i,$ch,$itm,$d,$incomm);
    my @arr = ();
    $itm = '';
    $incomm = 0;
    $d = '';
    for ($i = 0; $i < $len; $i++) {
        $ch = substr($ln,$i,1);
        if ($incomm) {
            $itm .= $ch;
            $incomm = 0 if ($ch eq $d);
        } else {
            if ($ch =~ /('|")/) {
                $d = $ch;
                $itm .= $ch;
                $incomm = 1;
            } elsif ($ch eq ',') {
                push(@arr,$itm) if (length($itm));
                $itm = '';
            } else {
                if ($ch =~ /\s/) {
                    $itm .= $ch if (length($itm));
                } else {
                    $itm .= $ch;
                }
            }
        }
    }
    push(@arr,$itm) if (length($itm));
    return @arr;
}

sub process_file($) {
    my ($inf) = @_;
    if (!open INF, "<$inf") {
        pgm_exit(1,"ERROR: Can NOT open file [$inf]! Check name, location...\n");
    }
    my @lines = <INF>;
    close INF;
    my $lncnt = scalar @lines;
    prt("Processing $lncnt files from [$inf]\n");
    my $func = "function MainMenu2()";
    my $arr = 'var ma = new Array(';
    my $lnbgn = 'new Item';
    my ($i,$line,$infunc,$lnn,$inset,@braces,$pc,$ch);
    my ($incomm,$j,$len,$set,@arr,$sc,$tit,$lnk,$num,$section,$ra);
    my ($snum,$key);
    # new Item('','','&nbsp; ',0), = section
    # new Item('Home','index.html','',1), = entry in section
    # comment /* ... */ or //
    $infunc = 0;
    $inset = 0;
    @braces = ();
    $ch = '';
    $incomm = 0;
    $section = '';
    $snum = 0;
    my %hash;
    for ($i = 0; $i < $lncnt; $i++) {
        $lnn = $i + 1;
        $line = trim_all($lines[$i]);
        $len = length($line);
        next if ($len == 0);
        for ($j = 0; $j < $len; $j++) {
            $pc = $ch;
            $ch = substr($line,$j,1);
            if ($incomm) {
                if (($ch eq '/')&&($pc eq '*')) {
                    $incomm = 0;
                }
                next;
            } elsif (($ch eq '*')&&($pc eq '/')) {
                $incomm = 1;
                next;
            }
            if ($ch eq '{') {
                push(@braces,$lnn);
            } elsif ($ch eq '}') {
                if (@braces) {
                    pop @braces;
                } else {
                    prtw("$lnn: WARNING: Got close braces, but none open...\n");
                }
            }
        }
        if ($line =~ /^function\s+MainMenu2/) {
            $infunc = 1;
            prt("$lnn: Begin function...\n");
        } elsif ($infunc) {
            if ($line =~ /^new\s+Item\s*\((.+)\)/) {
                $set = $1;
                $inset = 1;
                #@arr = split(',',$set);
                @arr = split_comma($set);
                $sc = scalar @arr;
                if ($sc == 4) {
                    # new Item('','','&nbsp; ',0), = section
                    # new Item('Home','index.html','',1), = entry in section
                    $num = $arr[3];
                    if ($arr[0] eq "''") {
                        $section = gm_strip_both_quotes($arr[2]);
                        $section =~ s/&nbsp;/-/;
                        $section = trim_all($section);
                        #$section = 'Main' if (length($section) == 0);
                        $snum++;
                        $key = sprintf("%04d_$section",$snum);
                        prt("$lnn: Got set SECTION $section [$set]$num\n");
                    } else {
                        pgm_exit(1,"ERROR: No SECTION found!\n") if (length($section) == 0);
                        if (($section ne 'Development') || $include_all_sections) {
                            $tit = gm_strip_both_quotes($arr[0]);
                            $lnk = gm_strip_both_quotes($arr[1]);
                            prt("$lnn: Got set SUB $tit [$set]$num\n");
                            if (!defined $hash{$key}) {
                                $hash{$key} = [];
                            }
                            $ra = $hash{$key};
                            push(@{$ra}, [$tit,$lnk,$num]);
                        }
                    }
                } else {
                    prtw("$lnn: WARNING: Set is NOT 4 [$sc]!\n");
                }
            } else {
                if ($line =~ /\/\/\s+next\s+number/) {
                    $infunc = 0;
                    last;
                } elsif (!ignored_lines($line)) {
                    prtw("$lnn: WARNING: Line ignored??? [$line]\n");
                }
            }
        }
    }
    return \%hash;
}

sub get_html_head() {
    my $head = <<EOF;
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      lang="en"
      xml:lang="en">
 <head>
  <meta http-equiv="Content-Type"
        content="text/html; charset=us-ascii" />
  <meta name="Keywords"
        content=
        "free,gpl,flightgear,simgear,terragear,flight,simulator,simulation,world,scenery" />
<title>Test HTML</title>
  <style type="text/css">
/*<![CDATA[ page specific style */

/* FOOTER SECTION */

#footer {
clear: left;
width: 100%;
text-align: center;
padding: 0;
font-weight: bold;
border: 0;
border-top: 1px solid #9c9c9c;
/* background: #ffc0ff;  /* only for debug */
}

#footer a {
text-decoration: none;
}

#footer h4 ul li
{
border: 0px;
padding: 0px;
margin: 0px;
}

#footer ul li
{
text-align: left;
margin: 0px;
padding: 0px;
list-style-type: none;
/* font-family: sans-serif; */
}

.nombtd
{
text-decoration:none;
margin:0px;
padding:0px;
border:0px;
}
  /*]]>*/
  </style>
</head>
<body>
<h1 align="center">Test HTML</h1>
EOF
    return $head;
}

sub show_ref_hash($) {
    my ($rh) = @_;
    my ($key,$ra,$rac,$i,$tit,$lnk,$num,$sect);
    my $dir = $parent;
    my $msg = get_html_head();
    $msg .= "<p>Horizontal table generation... parent=[$parent]</p>\n";
    $msg .= "\n\n";
    $msg .= "<div id=\"footer\">\n";
    $msg .= "<table border=\"0\" width=\"100%\" cellspacing=\"2\" summary=\"Bottom TOC\" align=\"center\">\n";
    $msg .= "<tr>\n";
    foreach $key (sort keys %{$rh}) {
        $ra = ${$rh}{$key};
        prt("$key\n");
        $sect = $key;
        $sect =~ s/^\d+_//;
        $sect = 'Main' if ($sect eq '-');
        $msg .= "<td valign=\"top\">\n";
        $msg .= "<h4 class=\"nombtd\" align=\"left\">$sect</h4>\n";
        $msg .= "<ul class=\"nombtd\">\n";
        $rac = scalar @{$ra};
        for ($i = 0; $i < $rac; $i++) {
            $tit = ${$ra}[$i][0];
            $lnk = ${$ra}[$i][1];
            $num = ${$ra}[$i][2];
            prt(" [$lnk] [$tit] ($num)\n");
            if ((length($parent)) && !($lnk =~ /^http/i)) {
                $msg .= "<li><a href=\"".$parent.$lnk."\">$tit</a></li>\n";
            } else {
                $msg .= "<li><a href=\"$lnk\">$tit</a></li>\n";
            }
        }
        $msg .= "</ul>\n";
        $msg .= "</td>\n";
    }
    $msg .= "</tr>\n";
    $msg .= "</table>\n";
    $msg .= "FlightGear &copy; 2010+ all right reserved.\n";
    $msg .= "<a class=\"nombtd\" href=\"http://www.flightgear.org/%7Ecurt/\">Curtis L. Olson\n";
    $msg .= "<img class=\"nombtd\" src=\"$dir/images/email-fg2.png\" alt=\"Curt's email address\" /></a>\n";
    $msg .= "<a target=\"_blank\" href=\"http://tidy.sourceforge.net/\"><img class=\"nombtd\"\n";
    $msg .= "border=\"0\" src=\"$dir/images/checked_by_tidy.gif\" alt=\"checked by tidy\"\n";
    $msg .= "width=\"32\" height=\"32\" /></a>&nbsp; <a target=\"_blank\" href=\"http://validator.w3.org/check/referer\">\n";
    $msg .= "<img class=\"nombtd\" src=\"$dir/images/valid-xhtml10-blue.gif\"\n";
    $msg .= "alt=\"Valid XHTML 1.0!\" height=\"31\" width=\"88\" /></a>";
    $msg .= "<p class=\"nombtd\"><a href=\"#top\">top</a></p>\n";
    $msg .= "\n\n";

    $msg .= "<p>And now a vertical generation...</p>\n";
    $msg .= "\n\n";
    # now a vertical menu
    foreach $key (sort keys %{$rh}) {
        $ra = ${$rh}{$key};
        #prt("$key\n");
        $sect = $key;
        $sect =~ s/^\d+_//;
        $sect = '&nbsp;' if ($sect eq '-');
        $msg .= "<h4 class=\"nombtd\" align=\"left\">$sect</h4>\n";
        $msg .= "<ul class=\"nombtd\">\n";
        $rac = scalar @{$ra};
        for ($i = 0; $i < $rac; $i++) {
            $tit = ${$ra}[$i][0];
            $lnk = ${$ra}[$i][1];
            $num = ${$ra}[$i][2];
            prt(" $lnk $tit $num\n");
            if ((length($parent)) && !($lnk =~ /^http/i)) {
                $msg .= "<li><a href=\"".$parent.$lnk."\">$tit</a></li>\n";
            } else {
                $msg .= "<li><a href=\"$lnk\">$tit</a></li>\n";
            }
        }
        $msg .= "</ul>\n";
    }

    $msg .= "</div>\n";
    $msg .= "\n\n";

    # try for a javascript generator
    if ($gen_javascript) {
        $msg .= "<p>And a script generator...</p>\n";
        $msg .= "<pre>function MainMenu4(\$root) {\n";
        $msg .= "  document.write(\"<div id=\\\"bottomtoc\\\">\");\n";
        $msg .= "  document.write(\"<table border=\\\"0\\\" cellspacing=\\\"2\\\" summary=\\\"Bottom TOC\\\" align=\\\"center\\\">\");\n";
        $msg .= "  document.write(\"<tr>\");\n";
        foreach $key (sort keys %{$rh}) {
            $ra = ${$rh}{$key};
            #prt("$key\n");
            $sect = $key;
            $sect =~ s/^\d+_//;
            $sect = 'Main' if ($sect eq '-');
            $msg .= "  document.write(\"<td valign=\\\"top\\\">\");\n";
            $msg .= "  document.write(\"<h4 class=\\\"nombtd\\\" align=\\\"left\\\">$sect</h4>\");\n";
            $msg .= "  document.write(\"<ul class=\\\"nombtd\\\">\");\n";
            $rac = scalar @{$ra};
            for ($i = 0; $i < $rac; $i++) {
                $tit = ${$ra}[$i][0];
                $lnk = ${$ra}[$i][1];
                $num = ${$ra}[$i][2];
                #prt(" $lnk $tit $num\n");
                if ($lnk =~ /^http/) {
                    $msg .= "  document.write(\"<li><a href=\\\"$lnk\\\">$tit</a></li>\");\n";
                } else {
                    $msg .= "  document.write(\"<li><a href=\\\"\" + \$root + \"/$lnk\\\">$tit</a></li>\");\n";
                }
            }
            $msg .= "  document.write(\"</ul>\");\n";
            $msg .= "  document.write(\"</td>\");\n";
        }
        $msg .= "  document.write(\"</tr>\")\n";
        $msg .= "  document.write(\"</table>\")\n";
        $msg .= "  document.write(\"</div>\")\n";
        $msg .= "}\n";
        $msg .= "</pre>\n";
    }

    $msg .= "</body>\n";
    $msg .= "</html>\n";
    return $msg;
}

#########################################
### MAIN ###
prt( "$pgmname: in [$cwd]: Hello, World...\n" );
my $ref_hash = process_file($in_file);
my $html = show_ref_hash($ref_hash);
write2file($html,$out_file);
prt("Written $out_file\n");
system($out_file);
pgm_exit(0,"Normal exit(0)");
########################################
# eof - template.pl
