#!/usr/bin/perl -w
# NAME: addjsnav.pl
# AIM: QUITE SPECIALIZED! Seek all HTML in folder given, and add a nav.js script,
# and insert a printList() js in 'docs' div...
use strict;
use warnings;
use File::Basename;  # split path ($name,$dir,$ext) = fileparse($file [, qr/\.[^.]*/] )
use Cwd;
my $os = $^O;
my $perl_dir = '/home/geoff/bin';
my $PATH_SEP = '/';
my $temp_dir = '/tmp';
if ($os =~ /win/i) {
    $perl_dir = 'C:\GTools\perl';
    $temp_dir = $perl_dir;
    $PATH_SEP = "\\";
}
unshift(@INC, $perl_dir);
require 'lib_utils.pl' or die "Unable to load 'lib_utils.pl' Check paths in \@INC...\n";
# log file stuff
our ($LF);
my $pgmname = $0;
if ($pgmname =~ /(\\|\/)/) {
    my @tmpsp = split(/(\\|\/)/,$pgmname);
    $pgmname = $tmpsp[-1];
}
my $outfile = $temp_dir.$PATH_SEP."temp.$pgmname.txt";
open_log($outfile);

# user variables
my $VERS = "0.0.1 2013-03-17";
my $load_log = 0;
my $in_file = '';
my $verbosity = 0;
my $out_file = '';
my $show_script = 0;

# ### DEBUG ###
my $debug_on = 1;
#my $def_file = 'C:\Projects\OpenLayers\OpenLayers-2.12\examples';
#my $def_file = 'C:\Projects\OpenLayers\OpenLayers-2.12\examples\browser.html';
my $def_file = 'C:\Projects\OpenLayers\OpenLayers-2.12\examples\mvs.html';
### program variables
my @warnings = ();
my $cwd = cwd();

my @excluded_files = qw(browser.html);

sub VERB1() { return $verbosity >= 1; }
sub VERB2() { return $verbosity >= 2; }
sub VERB5() { return $verbosity >= 5; }
sub VERB9() { return $verbosity >= 9; }

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

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


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

sub is_excluded($) {
    my $f = shift;
    my ($tst);
    my ($name,$dir) = fileparse($f);
    foreach $tst (@excluded_files) {
        return 1 if ($tst =~ /^$name$/i);
    }
    return 0;
}

sub is_html_file($) {
    my $f = shift;
    return 0 if (is_excluded($f));
    return 1 if ($f =~ /\.html$/);
    return 0;
}

sub get_attr_hash($) {
    my $txt = shift;
    my $len = length($txt);
    my ($i,$ch,$cc,$tag,$val,$getval);
    my %h = ();
    $tag = '';
    $val = '';
    $getval = 0;
    for ($i = 0; $i < $len; $i++) {
        $ch = substr($txt,$i,1);
        if ($getval) {
            if (($ch eq '"')||($ch eq "'")) {
                if (length($val)) {
                    $h{$tag} = $val if (length($tag));
                    $getval = 0;
                    $tag = '';
                    $val = '';
                } else {
                    $cc = $ch;
                }
            } elsif ($ch =~ /\s/) {
                if (length($val)) {
                    $val .= $ch;
                }
            } else {
                $val .= $ch;
            }
        } else {
            if ($ch eq '=') {
                $getval = 1;
                $cc = '';
                $val = '';
            } elsif ($ch =~ /\s/) {
                # what is this
            } else {
                $tag .= $ch;
            }
        }

    }
    if ($getval && length($tag)) {
        $h{$tag} = $val;
    } elsif (length($tag)) {
        $h{$tag} = 1;
    }
    return \%h;
}

sub process_html_file($) {
    my $file = shift;
    if (!open INF, "<$file") {
        prtw("WARNING: Failed to open [$file]\n");
        return 1;
    }
    my @lines = <INF>;
    close INF;
    my $lncnt = scalar @lines;
    prt("Process $lncnt lines from $file\n");
    my ($i,$line,$len,$tline,$j,$ch,$tag,$inquot,$qc,$pc,$intag,$attr,$int,$lnn,$bgn,$rh);
    my ($key,$val,$divcnt,$tmp,$msg,$script,$rem);
    my @nlines = ();
    $ch = '';
    $lnn = 0;
    $divcnt = 0;
    my $inscript = 0;
    my $incomment = 0;
    my $inhtml = 0;
    my $inhead = 0;
    my $inbody = 0;
    for ($i = 0; $i < $lncnt; $i++) {
        $line = $lines[$i];
        chomp $line;
        $lnn++;
        $tline = trim_all($line);
        $len = length($tline);
        if ($len == 0) {
            push(@nlines,"");
            next;
        }
        $len = length($line);
        # process the line
        $intag = 0;
        $int = 0;
        $attr = '';
        $tag = '';
        for ($j = 0; $j < $len; $j++) {
            $pc = $ch;
            $ch = substr($line,$j,1);
            if ($ch eq '<') {
                $bgn = $lnn;
                prt("Start tag [$tline]\n") if (VERB9());
                $rem = substr($line,$j);
                # if had a tag
                if ($inscript) {
                    if ($rem =~ /^<\/script>/i) {
                        $inscript = 0;
                        prt("$lnn: End script [$script]\n") if ($show_script || VERB9());
                        $script = '';
                    } else {
                        $script .= $ch;
                        next;
                    }
                } elsif ($rem =~ /^<!--/) {
                    prt("$bgn: BEGIN COMMENT\n");
                    $incomment = 1;
                } else {
                    $intag = 1;
                }

                if (length($tag)) {
                    prt("BGN $bgn <$tag");
                    prt(" ATTR: $attr") if (length($attr));
                    prt("> END $lnn \n");
                }
                # restart tag and attr
                $tag = '';
                $attr = '';
                $inquot = 0;
                $int = 0;
            } elsif ($incomment) {
                if ($ch eq '-') {
                    $rem = substr($line,$j);
                    if ($rem =~ /-->/) {
                        prt("$lnn: END COMMENT\n");
                        $incomment = 0;
                    }
                }
            } elsif ($intag) {
                if ($ch eq '>') {
                    $intag = 0;
                    prt("End   tag [$tline]\n") if (VERB9());
                    # if had a tag
                    $msg = '';
                    if (length($tag)) {
                        $rh = get_attr_hash($attr);
                        if ($tag =~ /^\//) {
                            # closing tag
                            $tmp = substr($tag,1);
                            if ($tmp =~ /^html$/i) {
                                $inhtml = 0;
                                $msg .= ' END HTML';
                            } elsif ($tmp =~ /^head$/i) {
                                $inhead = 0;
                                $msg .= ' END HEAD';
                            } elsif ($tmp =~ /^body$/i) {
                                $inbody = 0;
                                $msg .= ' END BODY';
                            } elsif ($tmp =~ /^script$/i) {
                                $inscript = 0;
                            } elsif ($tmp =~ /^div$/i) {
                                if ($divcnt) {
                                    $divcnt--;
                                    $msg .= " DIV CLOSE $divcnt";
                                } else {
                                    prtw("WARNING: $lnn: Close DIV when NOT open! $file\n");
                                }
                            }

                        } elsif ($tag =~ /^!/) {
                            # special
                        } else {
                            # open a tag
                            if ($tag =~ /^html$/i) {
                                $inhtml = 1;
                            } elsif ($tag =~ /^head$/i) {
                                $inhead = 1;
                            } elsif ($tag =~ /^body$/i) {
                                $inbody = 1;
                            } elsif ($tag =~ /^script$/i) {
                                $inscript = 1;
                                $msg .= " BEGIN SCRIPT";
                            } elsif ($tag =~ /^div$/i) {
                                $divcnt++;
                                $msg .= " DIV OPEN $divcnt";
                            }
                        }
                        prt("Bgn $bgn <$tag");
                        if (length($attr)) {
                            prt(" attr: $attr");
                            prt(" rh: ");
                            $attr = '';
                            foreach $key (keys %{$rh}) {
                                $val = ${$rh}{$key};
                                prt(" ") if (length($attr));
                                prt("$key=\"$val\"");
                                $attr .= $key;
                            }
                        }
                        prt("> End $lnn $msg\n");
                        $tag = '';
                        $attr = '';
                    }
                    $tag = '';
                    $attr = '';
                } else {
                    if ($int) {
                        $attr .= $ch;
                    } else {
                        if ($ch =~ /\s/) {
                            $int = 1;
                        } else {
                            $tag .= $ch;
                        }
                    }
                }
            } elsif ($inscript) {
                $script .= $ch;
            }
        }
        $script .= "\n" if ($inscript);
        push(@nlines,$line);
    }
    return 0;
}


sub process_html_files($) {
    my $ra = shift;
    my ($max,$i);
    $max = scalar @{$ra};
    prt("Got $max files to process,,,\n");
    my ($file);
    foreach $file (@{$ra}) {
        process_html_file($file);
    }
}


sub process_in_dir($) {
    my ($inf) = @_;
    if (! opendir( DIR, "$inf") ) {
        pgm_exit(1,"ERROR: Unable to open directory [$inf]\n"); 
    }
    my @files = readdir(DIR);
    closedir(DIR);
    my $lncnt = scalar @files;
    prt("Processing $lncnt files, from [$inf]...\n");
    my ($i,$file,$ff,$cnt);
    ut_fix_directory(\$inf);
    my @dirs = ();
    my @html = ();
    for ($i = 0; $i <  $lncnt; $i++) {
        $file = $files[$i];
        next if ($file eq '.');
        next if ($file eq '..');
        $ff = $inf.$file;
        if (-d $ff) {
            push(@dirs,$ff);
        } elsif (is_html_file($file)) {
            prt("Process $ff..\n") if (VERB9());
            push(@html,$ff);
        } else {
            #prtw("WARNING: WHAT IS THIS? [$ff]\n");
        }
    }
    $cnt = scalar @html;
    prt("Got $cnt html files to process...\n");
    process_html_files(\@html);
}

#########################################
### MAIN ###
parse_args(@ARGV);
if (-f $in_file) {
     process_html_file($in_file);
} else {
    process_in_dir ($in_file);
}
pgm_exit(0,"");
########################################

sub need_arg {
    my ($arg,@av) = @_;
    pgm_exit(1,"ERROR: [$arg] must have a following argument!\n") if (!@av);
}

sub parse_args {
    my (@av) = @_;
    my ($arg,$sarg);
    while (@av) {
        $arg = $av[0];
        if ($arg =~ /^-/) {
            $sarg = substr($arg,1);
            $sarg = substr($sarg,1) while ($sarg =~ /^-/);
            if (($sarg =~ /^h/i)||($sarg eq '?')) {
                give_help();
                pgm_exit(0,"Help exit(0)");
            } elsif ($sarg =~ /^v/) {
                if ($sarg =~ /^v.*(\d+)$/) {
                    $verbosity = $1;
                } else {
                    while ($sarg =~ /^v/) {
                        $verbosity++;
                        $sarg = substr($sarg,1);
                    }
                }
                prt("Verbosity = $verbosity\n") if (VERB1());
            } elsif ($sarg =~ /^l/) {
                if ($sarg =~ /^ll/) {
                    $load_log = 2;
                } else {
                    $load_log = 1;
                }
                prt("Set to load log at end. ($load_log)\n") if (VERB1());
            } elsif ($sarg =~ /^o/) {
                need_arg(@av);
                shift @av;
                $sarg = $av[0];
                $out_file = $sarg;
                prt("Set out file to [$out_file].\n") if (VERB1());
            } else {
                pgm_exit(1,"ERROR: Invalid argument [$arg]! Try -?\n");
            }
        } else {
            $in_file = $arg;
            prt("Set input to [$in_file]\n") if (VERB1());
        }
        shift @av;
    }

    if ($debug_on) {
        prtw("WARNING: DEBUG is ON!\n");
        if (length($in_file) ==  0) {
            $in_file = $def_file;
            prt("Set DEFAULT input to [$in_file]\n");
        }
    }
    if (length($in_file) ==  0) {
        pgm_exit(1,"ERROR: No input files found in command!\n");
    }
    if ( -f $in_file) {
        # process a simgle file
    } elsif (! -d $in_file) {
        pgm_exit(1,"ERROR: Unable to find directory [$in_file]! Check name, location...\n");
    }
}

sub give_help {
    prt("$pgmname: version $VERS\n");
    prt("Usage: $pgmname [options] in-dir\n");
    prt("Options:\n");
    prt(" --help  (-h or -?) = This help, and exit 0.\n");
    prt(" --verb[n]     (-v) = Bump [or set] verbosity. def=$verbosity\n");
    prt(" --load        (-l) = Load LOG at end. ($outfile)\n");
    prt(" --out <file>  (-o) = Write output to this file.\n");
}

# eof - template.pl
