#!/usr/bin/perl -w

=head1 NAME

header.pl - create tobert.org

=head1 WARNING

I wrote this before I learned TT2.   It is not a good idea to write your own
templating system, except when it is.

=cut

use strict;
use Carp;
use CGI::Pretty qw(:standard);
use File::Find;
use File::Path;
use File::Copy;
use File::Basename;
use Tie::IxHash;
our( $publish_dir, $email, %nav_links, @gallery_files ) = ();

$publish_dir = '/srv/tobert.org';
#$publish_dir = '/tmp/tobert.org-publish';
mkdir( $publish_dir );
$email = 'tobert@gmail.com';
tie %nav_links, 'Tie::IxHash';
%nav_links = (
    l_home       => [ "index.html",            "Home"       ],
    #l_blog       => [ "http://albertptobey.blogspot.com", "Blog" ],
    #l_lnkdn      => [ "http://www.linkedin.com/pub/3/5b8/600", "Linkedin" ],
    l_perl       => [ "perl.html",             "Perl Stuff" ],
    l_unix       => [ "unix/index.html",       "Unix Stuff" ],
    l_resume     => [ "resume.html",           "Resume"     ],
#    l_tobert     => [ "tobert.html",           "About Me"   ],
    l_gallery    => [ "gallery/index.html",    "Images"     ],
#    l_automotive => [ "automotive/index.html", "Automotive" ],
    email        => [ "mailto:$email",         "Email Me"   ],
    x_picasa     => [ "/gallery/index.html",   "Gallery"    ]
);

# process everything else
find( {wanted => \&wanted, no_chdir => 1}, "." );

perltidy_header_pl();

# generate a couple POD files 
if ( -x '/usr/bin/pod2html' ) {
    pod2html( "$publish_dir/downloads/Search.pm" );
    pod2html( "$publish_dir/downloads/Kit.pm" );
}

print "Cleanup publishing directory command:\n",
      "    rm -rf $publish_dir\n",
      "Rsync push command:\n",
      "    rsync --delete --exclude=stats -acve ssh $publish_dir/./ USERNAME\@tobert.org:tobert-www/\n";

exit 0;

sub wanted {
    my $fname = $File::Find::name;
    return if ( -d $fname );
    return if ( $fname =~ /^\..*\.swp$/ );
    $fname =~ s/^\.//;
    $fname =~ s#^/##;

    my $pdir  = mkpubdir( $fname );

    #print "current file: $fname => $pdir\n";

    if ( $fname =~ m#gallery/[-\w]+/\w+.html$# ) {
        process_picasa_html( $fname, $pdir );
    }
    elsif ( $fname =~ /\.html$/ ) {
        process_html( $fname, $pdir );
    }
    elsif ( $fname =~ /header.pl$/ ) {
        # generate html with perltidy or vim
    }
    else {
        copy( $fname, pubfile($pdir,$fname) );
        printf "copy( $fname, %s ); %s\n", pubfile($pdir,$fname), $!;
    }

    copy( "tobert.css", "$pdir/tobert.css" );
}

sub process_html {
    my( $filename, $pdir ) = @_;
    open( HTML, "<$filename" )
        || die "could not open '$filename' for reading: $!";

    my $pubfile = pubfile( $pdir, $filename );
    open( PUB, ">$pubfile" )
        || die "could not open '$pubfile' for writing: $!";

    my $page_id = '';
    while ( my $line = <HTML> ) {
        next if ( $line =~ /^\s*[\r\n]$/ );
        # requires the body tag to be in a pretty specific format ...
        if ( $line =~ /<body id="(\w+)"/i ) {
            $page_id = $1;
            if ( $page_id =~ /resume$/ ) {
                print PUB $line;
            }
        }
        if ( $line =~ /<code>/ ) {
            print PUB $line;
            while ( my $line = <HTML> ) {
                $line =~ s/&/&amp;/g;
                print PUB $line;
                last if ( $line =~ /<\/code>/ );
            }
        }
        elsif ( $line =~ /%%(\w+)%%/ ) {
            my $tag = $1;
            if ( $tag eq 'HEADER' ) {
                print PUB mkheader( $page_id );
            }
            elsif ( $tag eq 'NAVMENU' ) {
                print PUB mkmenu( $page_id, $filename );
            }
            elsif ( $tag eq 'FOOTER' ) {
                print PUB mkfooter( $page_id );
            }
            elsif ( $tag eq 'BEGIN' ) {
                print PUB "<div id=\"stuff\">\n";
            }
            elsif ( $tag eq 'END' ) {
                print PUB "</div>\n";
            }
        }
        else {
            print PUB $line;
        }
    }

    close( PUB );
    close( HTML );
}

sub process_picasa_html {
    my( $filename, $pdir ) = @_;
    open( HTML, "<$filename" )
        || die "could not open '$filename' for reading: $!";

    my $pubfile = pubfile( $pdir, $filename );
    open( PUB, ">$pubfile" )
        || die "could not open '$pubfile' for writing: $!";

    while ( my $line = <HTML> ) {
        $line =~ s/[\r\n]//g;

        if ( $line =~ /<link rel="stylesheet" href="style.css"/ ) {
            $line =~ s#style.css#../../tobert.css#g;
            print PUB $line, $/;
        }
        elsif ( $line =~ /^<body (.*)>\s*$/i ) {
            print PUB "<body $1>$/";
            print PUB mkmenu( 'x_picasa', $filename ), $/;
            print PUB "<div id=\"stuff\">$/<img src=\"logo.gif\" alt=\"Picasa Logo\"/>$/";
        }
        elsif ( $line =~ m#</body># ) {
            print PUB "</div>$/$line$/";
        }
        else {
            $line =~ s/<hr size="1">/<hr><br>/gi;
            print PUB $line, $/;
        }
    }

    close( PUB );
    close( HTML );
}

sub mkheader {
    my $id = shift;
    my $title = $nav_links{$id}->[1] || "";
    #<base href="http://www.tobert.org/" />
    return <<EOHTML;
<!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" xml:lang="en" lang="en">

<head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
    <link rel="stylesheet" type="text/css" media="screen" href="tobert.css"/>
    <title>$title</title>
    <meta http-equiv="imagetoolbar" content="no" />
    <meta http-equiv="author" content="Al Tobey"/>
    <meta http-equiv="generated-by" content="/usr/bin/perl header.pl"/>
    <style type="text/css">
        body {
            background-color: #000000;
            color: #ffffff;
        }
    </style>
</head>
<body id="$id">
EOHTML
}

sub mkmenu {
    my( $id, $filename ) = @_;

    my $depth = 0;
    for ( split '/', $filename ) { $depth++ }

    my $name = $nav_links{$id}->[1];

    #<h2>Al Tobey's Pages [$name]</h2>
    my $html = <<EOHTML;
<div id="navigation">
    <ul>
EOHTML
    foreach my $nav_id ( keys %nav_links ) {
        next if ( $nav_id =~ /^x_/ );
        my $ctag = ''; 
        if ( $nav_id eq $id ) {
            $ctag = ' id="current"';
        }

        my $to = $nav_links{$nav_id}->[0];
        my $name = $nav_links{$nav_id}->[1];

	next unless ( $to && $name );

        for ( my $i=1; $i<$depth; $i++ ) {
            next if ( $to =~ /^(?:http|https|mailto):/ );
            $to = '../' . $to;
        }

        $html .= sprintf "      <li%s><a href=\"%s\">%s</a></li>\n",
                         $ctag, $to, $name;
    }
    $html .= <<EOHTML;
    </ul>
</div>
EOHTML
}

sub mkfooter {
    my $id = shift;
    return <<EOHTML;
</body>
</html>
EOHTML
}

sub slurp {
    return '' if ( !-f $_[0] );
    open( FILE, "<$_[0]" );
    my $old = $/;
    $/ = undef;
    my $rv = <FILE>;
    $/ = $old;
    close( FILE );
    chomp( $rv );
    return $rv;
}

sub mkpubdir ($) {
    my $filename = shift;

    if ( !-d $filename ) {
        $filename = dirname( $filename );
    }

    if ( ! -d "$publish_dir/$filename" ) {
        mkpath( "$publish_dir/$filename" )
            || die "could not create $publish_dir/$filename: $!";
    }

    return "$publish_dir/$filename"
}

sub pubfile ($$) {
    my( $pdir, $filename ) = @_;
    my $bname = basename( $filename );
    return "$pdir/$bname";
}

sub perltidy_header_pl {
    # 100% pure cheese (will get munged in web display)
    system( "perltidy -pre -html -o=/tmp/header.pl.html.pre $0" );
    open( my $html, "< /tmp/header.pl.html.pre" )
        || die "could not open /tmp/header.pl.html.pre for reading: $!";
    open( my $out, "> $publish_dir/header_pl.html" )
        || die "could not open $publish_dir/header_pl.html for writing: $!";
    while ( <$html> ) {
        s/USERNAME/USERNAME/g;
        print $out $_;
    }
    unlink( "$publish_dir/header.pl" );
}

sub pod2html {
    my $pmfile = shift;
    return unless ( -x '/usr/bin/pod2html' );
    my $tmpfile = $pmfile . ".html.tmp";
    my $htmlfile = $pmfile . ".html";
    my $shortfile = $htmlfile; $shortfile =~ s#.*/downloads/#/downloads/#;

    system( "pod2html --css=/downloads/perl.css $pmfile > $tmpfile" );

    open( my $fh, "< $tmpfile" );
    unlink $tmpfile;
    open( my $out, "> $htmlfile" );

    while ( my $line = <$fh> ) {
        if ( $line =~ /<body.*$/ ) {
            print $out $line;
            print $out mkmenu( 'pod', $shortfile ), $/;
            print $out "<div id=\"stuff\">$/";
        }
        elsif ( $line =~ /<\/body>/ ) {
            print $out "</div>\n</body>\n";
        }
        else {
            print $out $line;
        }
    }
    close $fh;
    close $out;
}