#!/usr/bin/perl
#
# Simple CGI "server" for the WebTechniques Tclet demo
# N.B. no data checking is done here everything is done
# in the Tclet
#
# written by Chris Baron for WebTechniques Magazine
#
$password = 'froboz';
$db_dir = '';

use CGI; # use the CGI.pm module 
         # http://www-
genome.wi.mit.edu/ftp/distribution/software/WWW/
$| = 1;  # turn off buffering

print "content-type: text/plain\n\n";  # all we send is plain text
$f = new CGI; # get form data
if ($f->param('password') ne $password) { &error_exit; } # check pw
if ($f->param('action') eq 'fetch') { &fetch_db; }
elsif ($f->param('action') eq 'update') { &update_db; }
else { &error_exit; }
exit; # end of main program

sub fetch_db {
  if ($f->param('database') eq '') { &error_exit; }
  open (DATABASE, $db_dir.$f->param('database')) || &error_exit;
  while (<DATABASE>) { print; }
  close DATABASE;
}

sub update_db {
  if ($f->param('database') eq '') { &error_exit; }
  @records = $f->param('data');
  # we should lock database here
  open (DATABASE, '>'.$db_dir.$f->param('database')) || &error_exit;
  foreach (@records) { 
     if ($_) { print DATABASE $_, "\n"; }
  }
  close DATABASE;
  # unlock database here
  print "OK\n";
}

sub error_exit {
   print "Error\n";
   exit;
}