#!/usr/bin/perl

# stem.cgi

# todo - 
# html_escape image names and annotations
# mailto the annotation email only if it contains an @

# silly - 
# auto-generate thumbnails?
# make symlinks work
# image (or directory) contains an ahref?
# search should cope with plurals
 
use strict;
use warnings;

use lib qw(/home/blech/perllib/perl5
           /home/blech/perllib/share/perl/5.8.4
	              /home/blech/perllib/lib/perl/5.8.4
		                 /home/blech/perllib/lib/home/blech/perllib/
				/home/blech/web/husk.org/pics);
use Data::Dumper;
use Stem;

use CGI qw/:standard/;
use Template;
use File::Basename;

my $errors = Stem::Config::test_config();
if (scalar(@{$errors})) {
  foreach my $error (@{$errors}) {
    print STDERR $error."\n";
  }
  print "\n";
  exit(-1);
}

my $template = Template->new({INCLUDE_PATH => Stem::Config::get('template_dir')})
							 || die "template error\n";
my ($vars, $template_file); # TT globals

my $stem = Stem->new();
my ($command, $param) = $stem->dispatch();

if ($command eq 'search') {
  my $search = Stem::Search->new();

  $vars      = $search->build($param);
  $template_file = Stem::Config::get($vars->{template});
}

elsif ($command eq 'view') {
  # todo - make params safe

  my $view = Stem::View->new();
  my ($email, $comment) = (param('email'), param('comment'));

  $vars    = $view->build($param, $email, $comment);
  $template_file = Stem::Config::get('view_template');
}

else {
  my $browse = Stem::Browse->new();

  $vars          = $browse->build($param) if ($command eq 'browse');
  $vars          = $browse->rss()         if ($command eq 'rss');
  $vars          = $browse->front()       if (!defined $vars);

  if ($command eq 'browse' || $command eq 'rss') {
    $template_file = Stem::Config::get("${command}_template");
	} else {
    $template_file = Stem::Config::get('front_template');
  }
}

my $common_vars = $stem->vars();
map { $vars->{$_} = $common_vars->{$_} } keys (%{ $common_vars });
$vars->{'contenttype'} = $command;

my $contenttype = ($command eq 'rss') ? 'text/xml' : 'text/html';

# actually output
print header($contenttype);
$template->process($template_file, $vars) || die $template->error(), "\n";

__END__

=head1 NAME

stem.cgi - interface to CGI

=head1 CVS

$Header: /home/cvsroot/public/stem/stem.cgi,v 1.2 2003/04/06 11:34:34 blech Exp $

=head1 AUTHOR

Andy McFarland <andym@slab.org>
Paul Mison     <paulm@husk.org>
