#!/opt/perl/bin/perl -T

BEGIN {
	$::BASEDIR = "./cms";
	unshift(@INC, "$::BASEDIR/src");
	chdir("..");
}

use strict;
use warnings;
use CGI;
use CGI::Carp "fatalsToBrowser";
use CGI::Fast;
use Siikir;

while (my $fast = CGI::Fast->new) {
	$::TIME_START = time();
	my $cms = Siikir->new(
		root  => "$::BASEDIR",
		debug => 0,
		cgi   => $fast,
	);
	$cms->loadPlugin("Web");

	# RiveScript-specific hacks.
	if ($ENV{QUERY_STRING} =~ /^p=blog/) {
		# Old blog request.
		$cms->loadPlugin("Blog");
		$cms->loadPlugin("CGI");
		$cms->loadPlugin("JsonDB");
		my $param = $cms->CGI->params();

		# Find the current blog post for this.
		my $index = $cms->Blog->getIndex(1);
		my $fid   = $index->{ $param->{id} }->{fid};

		# Redirect them.
		if (defined $fid) {
			print "Status: 301 Moved Permanently\n"
				. "Location: http://$ENV{SERVER_NAME}/blog/kirsle/$fid\n\n";
			next;
		}
		else {
			print "Status: 301 Moved Permanently\n"
				. "Location: http://$ENV{SERVER_NAME}/blog/kirsle/$param->{id}\n\n";
			next;
		}
	}
	elsif ($ENV{QUERY_STRING} =~ /^p=(\w+)/) {
		print "Status: 301 Moved Permanently\n"
			. "Location: http://$ENV{SERVER_NAME}/$1\n\n";
		next;
	}
	elsif ($ENV{REQUEST_URI} =~ /^\/([A-Za-z0-9\-]+)\.html/i) {
		my $page = $1;
		my $query = length($ENV{QUERY_STRING}) ? "?$ENV{QUERY_STRING}" : "";
		print "Status: 301 Moved Permanently\n"
			. "Location: http://$ENV{SERVER_NAME}/$page$query\n\n";
		exit(0);
	}

	$cms->Page->run();
}
