#!/usr/bin/perl -w

# kupu_blog.cgi

# Example script that implements a rudimentary blogging
# application using kupu within a HTML form

use CGI;

my $template = '/var/www/craic_external/html/oreilly/kupu/blog_template.html';
my $filePath = '/var/www/craic_external/html/oreilly/kupu/blogdir';
my $htmlPath = 'http://www.craic.com/oreilly/kupu/blogdir';
my $srcFile  = 'http://www.craic.com/oreilly/kupu/kupu/common/kupublank.html';

my $cgi = new CGI;

# Load in a new entry if there is one
my $errorMsg = '';
my $newText = '';
if($cgi->param('kupu')) {
   $newText = $cgi->param('kupu');
   $newText =~ s/\>/\>\n/g;
   my $title = '';
   if($cgi->param('title')) {
      $title = $cgi->param('title');
      saveFile($filePath, $newText, $title);
   } else {
      $errorMsg = qq[<span style="color: red;">ERROR: No title was specified</span><br> <br>];
   }
}

# Load kupu template page

my $text = loadFile($template);

# Fetch existing entries

my $existingBlog = loadBlog($htmlPath, $filePath);

# Replace the placeholder variables in the template page

$text =~ s/\$errorMsg/$errorMsg/;
$text =~ s/\$srcFile/$srcFile/;
$text =~ s/\$existingBlog/$existingBlog/;

# Output the blog entries and the embedded kupu editor

print qq[Content-type: text/html\n\n];

print $text;

exit;


#--------------------------------------------------------------

sub loadFile {

   my $filename = shift;
   my $text = '';

   open INPUT, "< $filename" or die "$0: Unable to open file to read: $filename\n";
   while(<INPUT>) {
       $text .= $_;
   }
   close INPUT;

   $text;
}

#--------------------------------------------------------------

sub saveFile {

   # Save each blog entry to a separate file file__