My Blogging System

#! /usr/bin/perl -w

use HTML::TreeBuilder;
use Net::SFTP;

my $configFile="posted.files";

my @seenFiles=`cat $configFile`;
chomp(@seenFiles);

my @actualFiles=`md5sum \`du -a posts/* | cut -f2\``;
chomp(@actualFiles);

if(@seenFiles){

    @seenFiles=`md5sum \`cat $configFile\``;
    chomp(@seenFiles);

}else{

    my $actualHashRef = build_hash(\@actualFiles);
    my $seenHashRef = build_hash(\@seenFiles);

    #foreach $key (keys (%$actualHashRef)){ print "$actualHashRef->{$key}\n"; }

    foreach $key (keys (%$actualHashRef)){
        unless ($seenHashRef->{$key}){ 
            print "posting $actualHashRef->{$key}\n"; 
            build_indexhtml($actualHashRef->{$key});
            base_file($actualHashRef->{$key}, $configFile);
            sync_posts($actualHashRef->{$key});
        }
    }
}

sub build_hash {

     my $arrayRef = shift;
     my %actualHash;
     foreach (@$arrayRef){
        ($cksum,$file)=split(/\s+/,$_);
        $actualHash{$cksum}=$file;
     }
     return \%actualHash;
  
 }
    
sub base_file {
    my $fileToBase=$_[0];
    my $baseFile=$_[1];
    print "adding $fileToBase to $baseFile\n";
    open(BASEFILE, ">>$baseFile");
    print BASEFILE "$fileToBase\n";
    close(BASEFILE);
}

sub build_indexhtml {
 
    my $fileToPost=$_[0];

    my $title=`head -1 $fileToPost`;
    
    $title =~ s/<!--\s+//g;
    $title =~ s/\s+-->//g;

    my $tree = HTML::TreeBuilder->new;
    $tree->parse_file($fileToPost);

    my @style = $tree->look_down('_tag' => 'style');
    my @pre = $tree->look_down('_tag' => 'pre');
   
    `cp index.html index.html.orig`;

    # This updates the main page index.html 
    open(INDEXHTML, "< index.html");   
    @lines=<INDEXHTML>;
    close(INDEXHTML);

    open(INDEXHTML, "> index.html");
    my $inCut=0;
    foreach (@lines) {
            print INDEXHTML $_; 
            if (m/<!-- Main Content Column 1 start -->/){
                print INDEXHTML "<h2><a href=http://xyngon.com/$fileToPost>$title</a></h2>\n";   
                foreach (@pre) { print INDEXHTML $_->as_HTML(); }
            }
            if (m/<!-- Posts -->/){
                 print INDEXHTML "<li><a href=http://xyngon.com/$fileToPost>$title</a></li>";   
            }
    }
    close(INDEXHTML);

    open(CSS, "> codestyle.css");
    foreach (@style){ print CSS $_->as_HTML(); }
    close(CSS);

    $tree->delete;

}

sub sync_posts {

   my $file=shift;
   my $host="";
   my $user="";
   my $index="index.html";
   my $codestyle="codestyle.css";
   my $style="style.css";
   my %args = (ssh_args => []);
   push @{ $args{ssh_args} }, user => $user ;
   my $sftp = Net::SFTP->new($host,%args);
 
   print "putting $file\n";
   
   $sftp->put($file,"/home/xyngonc/www/$file"); 
   $sftp->put($index,"/home/xyngonc/www/$index");
   $sftp->put($style,"/home/xyngonc/www/$style");
   $sftp->put($codestyle,"/home/xyngonc/www/$codestyle");
}