#!/usr/bin/perl
#
# (pg)SQL-based diary
#

use CGI::SSI (autotie => STDOUT);
use DBI;
use Text::Template;
use CGI;

$db = "toodarkpark";
$dbUser = "howie";
$dbPass = "no1safe";
$dbHost="localhost";

$ENV{'PGHOST'} = $dbHost;

$INTRO_WORDS = 15;

$TEMPLATE_BASE_DIR = "/httpd/www.toodarkpark.net/misc/";
$tmplFile = "rss.template";
$WORDS_FILE = "$TEMPLATE_BASE_DIR/rss.words";

########################################################################

%connectHash =
(
        "AutoCommit" => 1,
        "RaiseError" => 0,
        "PrintError" => 0,
        "database"   => "$db",
        "username"   => "$dbUser",
        "password"   => "$dbPass"
);

########################################################################

MAIN:
{
	my( $cgi ) = new CGI();
	my( $conn );
	my( $sql );
	my( $res );
	my( $id ) = $cgi->param( "id" );

	#printf( "Content-type: application/rss+xml\n\n" );
	printf( "Content-type: text/xml\n\n" );

	&header();

	$conn = DBI->connect( "DBI:Pg:dbname=$db", $dbUser, $dbPass, \%connectHash) or die &footer();
	
	$newsQuery = "SELECT diary_id, title, contents, is_viewable, entry_date, entry_time FROM diary WHERE is_viewable='Y' ORDER BY entry_date desc, entry_time desc LIMIT 10";

	$res = $conn->prepare( $newsQuery );
	$res->execute();

	while( @row = $res->fetchrow_array() )
	{
		my( $diaryID, $title, $contents, $isViewable, $entryDate, $entryTime ) = @row;
		$contents = &removeLinks( $contents );

		## use at least $INTRO_WORDS words in our intro
		## neat since it avoids things like "hello i a..."
		## using instead "hello i am..."
		@words = split( / /, $contents );
		splice( @words, $INTRO_WORDS );
		$intro = join( ' ', @words );

		my( $timeHour, $timeMinute, $timeSecond ) = split( /:/, $entryTime );
		my( $time ) = sprintf( "%2.2d.%2.2d %s", ( $timeHour == 0 ? 12 : ( $timeHour > 12 ? $timeHour - 12 : $timeHour ) ), $timeMinute, $timeHour >= 12 ? "PM" : "AM" );

		my( $template ) = Text::Template->new( SOURCE => "$TEMPLATE_BASE_DIR/$tmplFile" ) || die "Failed to construct Text::Template: $Text::Template::ERROR";
		my( %templateVars );
		my( $dateYear, $dateMonth, $dateDay ) = split( /-/, $entryDate );

		$templateVars{'title'} = sprintf( "%s @ %s", $entryDate, $time );
		$templateVars{'intro'} = $intro;
		$templateVars{'diaryID'} = $diaryID;
		$templateVars{'dateYear'} = int($dateYear);
		$templateVars{'dateMonth'} = int($dateMonth);
		$templateVars{'dateDay'} = int($dateDay);
		$templateVars{'serverName'} = $ENV{'SERVER_NAME'};

		## id
		$templateVars{'id'} = $id;

		print $template->fill_in( HASH=> \%templateVars );
	}

	$res->finish();

	$conn->disconnect();

	&footer();
}
## use <link url="http://somewhere">text</link>
## will sub in target="new" and the like
sub removeLinks
{
        my( $text ) = shift( @_ );
        my( $value );

        ## maybe two passes -- one for link url="http://blah"
        ## and the other for link url="/foo/meh" ?

	$text =~ s/\<([^\>]+)\>([^\<]+)\<\/([^\>]+)\>/$2/g;
	$text =~ s/\<([^\>]+)\>//g;
	$text =~ s/\<\/([^\>]+)\>//g;

	$text =~ s/\n/ /g;

#        $text =~ s/\<link url=\"([^\"]+)\">([^\<]+)\<\/link\>/$2/g;
#        $text =~ s/\<a href=\"([^\"]+)\" target=\".*\">([^\<]+)\<\/a\>/$2/g;
#        $text =~ s/\<a href=\"([^\"]+)\">([^\<]+)\<\/a\>/$2/g;

        return $text;
}
sub header
{
print <<EOF
<?xml version="1.0" encoding="ISO-8859-1"?>
<rss version="2.0">
<channel>
<title>OMG LIEK RSS LOL</title>
<link>http://www.hmsphx.com/index.phtml?from=rss</link>
<description>Online journal of the coolest and sexiest person evar</description>
<language>en-us</language>
<copyright>1969-2036 HMS</copyright>

EOF
;
}

## footer
sub footer
{
print <<EOF

</channel>
</rss>
EOF
;
}
sub randomStringFromFile
{
   my( $file ) = shift( @_ );

   if( open( QUOTES, $file ) )
   {
      @allQuotes = <QUOTES>;
      close( QUOTES );
      $numQuotes = $#allQuotes;
      $randomNumber = int( rand( $numQuotes ) );
      $haiku = $allQuotes[$randomNumber];
      $haiku =~ s/\n//g;
   }
   else
   {
      @allLetters = ( "A", "B", "C" , "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" );
      $randomNumber = int( rand( 26 ) );
      $haiku = "This space brought to you by the letter " . $allLetters[$randomNumber];
   }

   return $haiku;
}
