#!/usr/bin/perl -I./lib
# 
# CGI-BIN script to show a webform with fields filled in
#
# Parameters: key=Key (number-random) of user.
#             db=DBFile
#             form=Formfile
#
use FileTable;

$debug = 1;

print STDERR "Remote host is $ENV{REMOTE_HOST}\n";
print STDERR "Remote addr is $ENV{REMOTE_ADDR}\n";
print STDERR "Remote ident is $ENV{REMOTE_IDENT}\n";

# Get the input - if cgi-bin, or argument, if not
if ($ARGV[0]) {
    $buffer = $ARGV[0];
    $debug = 1;
    print STDERR "Debug mode\n";
} elsif ($ENV{"QUERY_STRING"}) {
    $buffer = $ENV{"QUERY_STRING"};
    print STDERR "Query mode - read $buffer\n";
} else {
    read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
    print STDERR "Read $buffer\n";
}
@pairs = split(/&/, $buffer);
foreach $pair (@pairs)
{
    ($name, $value) = split(/=/, $pair);
    $value =~ tr/+/ /;
    $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;

    print STDERR "Setting $name to $value\n" if $debug;
    $entry{$name} = $value;
}

$filename = $entry{db};

eval '$records = FileTable::open($filename)';
if ($@) {
    dieform($@);
}

if ($entry{"key"}) {
    $key = $entry{"key"};
} else {
    dieform("You have to specify a key");
}

$record = $records->get($key);
if (!defined($record)) {
    dieform("Record not found for $index");
}

print <<EoF;
content-type: text/html

EoF
open(WWWFORM, $entry{form}) || dieform("Did not find $entry{form}\n");
while (<WWWFORM>) {
    if (/<INPUT NAME="(.*)"/i) {
	$field = $1;
	if ($record->{$field}) {
	    s/NAME="$field"/NAME="$field" VALUE="$record->{$field}"/i;
	}
    } elsif (/<SELECT NAME="(.*)"/i) {
	$select = 1;
	$field = $1;
	$val = $record->{$field};
	print STDERR "Checking for SELECT $field $val\n";
    } elsif ($select && /OPTION VALUE="$val"/i) {
	s/OPTION VALUE=/OPTION SELECTED VALUE=/i;
    } elsif (/<\/SELECT>/i) {
	$select = 0;
    }
    # Variable substitution, kind of...
    # <!> is a Processing Instruction in SGML, I think
    if (/<!([a-z0-9A-Z]+)>/ && $record->{$1}) {
	$field = $1;
	$value = $record->{$field};
	$value =~ s/\\n/<br>/g;
	s/<!$field>/$value/;
    }	
    print;
}

sub dieform {

    my $msg = shift;

    print <<EoF;
content-type: text/html

<html>
<head>
<title>Error message</title>
</head>
<body>
<h1>Error</h1>
Your request could not be completed.
<p>
Reason: $msg
<p>
<!-- appropriate BACK buttons go here -->
</body>
EoF
    die "Error $msg\n";
}

